package com.xnyzc.lhy.mis.service.impl.cms.order;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xnyzc.lhy.common.component.amap.GouldMapUtils;
import com.xnyzc.lhy.common.component.config.security.TokenUser;
import com.xnyzc.lhy.common.component.convert.DateToStringConverter;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.entity.GouldHistoryGps;
import com.xnyzc.lhy.common.entity.Qd;
import com.xnyzc.lhy.common.entity.Qw;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.cms.EVehicleType;
import com.xnyzc.lhy.common.penum.comment.EEvaluationIsShow;
import com.xnyzc.lhy.common.penum.order.*;
import com.xnyzc.lhy.common.penum.pay.EPayType;
import com.xnyzc.lhy.common.penum.vehicle.EBusinessType;
import com.xnyzc.lhy.common.penum.vehicle.ECallVehType;
import com.xnyzc.lhy.common.util.*;
import com.xnyzc.lhy.common.util.http.HttpRequestUtil;
import com.xnyzc.lhy.mis.entity.area.OaSysArea;
import com.xnyzc.lhy.mis.entity.cms.EXieChengResponseConstant;
import com.xnyzc.lhy.mis.entity.cms.CancelOrderRequest;
import com.xnyzc.lhy.mis.entity.cms.driver.DriverUserInfo;
import com.xnyzc.lhy.mis.entity.comment.OaSysComment;
import com.xnyzc.lhy.mis.entity.dictionaries.OaSysDict;
import com.xnyzc.lhy.mis.entity.gps.OaDVehicleGpsHistory;
import com.xnyzc.lhy.mis.entity.order.*;
import com.xnyzc.lhy.mis.entity.param.cms.PageVo;
import com.xnyzc.lhy.mis.entity.param.cms.order.CmsOadOrderPersonalParam;
import com.xnyzc.lhy.mis.entity.param.order.OaSysOrderDetails;
import com.xnyzc.lhy.mis.entity.param.order.OrderDetailRequest;
import com.xnyzc.lhy.mis.entity.param.order.OrderDetailResponse;
import com.xnyzc.lhy.mis.entity.result.cms.order.*;
import com.xnyzc.lhy.mis.entity.result.order.DriverOrderCard;
import com.xnyzc.lhy.mis.entity.result.order.OrderList;
import com.xnyzc.lhy.mis.entity.result.order.OrderLogMo;
import com.xnyzc.lhy.mis.entity.sidebar.OaSysOffice;
import com.xnyzc.lhy.mis.entity.system.OaSysBillRule;
import com.xnyzc.lhy.mis.entity.system.OaSysBillRuleGroup;
import com.xnyzc.lhy.mis.entity.system.OaSysUser;
import com.xnyzc.lhy.mis.entity.user.OaCUser;
import com.xnyzc.lhy.mis.entity.user.OaDUser;
import com.xnyzc.lhy.mis.entity.util.XieChengResponse;
import com.xnyzc.lhy.mis.entity.vehicle.OaSysVehicle;
import com.xnyzc.lhy.mis.mapper.area.OaSysAreaMapper;
import com.xnyzc.lhy.mis.mapper.comment.OaSysCommentMapper;
import com.xnyzc.lhy.mis.mapper.dictionaries.OaSysDictMapper;
import com.xnyzc.lhy.mis.mapper.gps.OaDVehicleGpsHistoryMapper;
import com.xnyzc.lhy.mis.mapper.order.*;
import com.xnyzc.lhy.mis.mapper.sidebar.OaSysOfficeMapper;
import com.xnyzc.lhy.mis.mapper.system.OaSysBillRuleGroupMapper;
import com.xnyzc.lhy.mis.mapper.system.OaSysBillRulesMapper;
import com.xnyzc.lhy.mis.mapper.system.OaSysUserMapper;
import com.xnyzc.lhy.mis.mapper.user.OaCUserMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserInfoMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserMapper;
import com.xnyzc.lhy.mis.mapper.vehicle.OaSysVehicleMapper;
import com.xnyzc.lhy.mis.mq.MqOrderProducer;
import com.xnyzc.lhy.mis.service.cms.order.CmsOrderInfoExportServer;
import com.xnyzc.lhy.mis.service.cms.order.ICmsOacOrderPersonalService;
import com.xnyzc.lhy.mis.service.cms.util.IOaSysGetOfficeIdListService;
import com.xnyzc.lhy.mis.util.XieChengUtil;
import com.xnyzc.lhy.mis.entity.user.OaDUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Function;

import static com.xnyzc.lhy.common.constant.MqConstant.LOG_OPERATE_ORDER;


/**
 * 自费叫车订单管理
 *
 * @Author conglijuan
 */
@Slf4j
@Service
@Component
public class CmsOacOrderPersonalServiceImpl implements ICmsOacOrderPersonalService {


    @Autowired
    private OaCOrderPersonalMapper oacOrderPersonalMapper;

    @Autowired
    private OaDUserMapper oadUserMapper;

    @Autowired
    private OaSysVehicleMapper oaSysVehicleMapper;

    @Autowired
    private IOaSysGetOfficeIdListService iOaSysGetOfficeIdListService;

    @Autowired
    private OaCUserMapper oacUserMapper;

    @Autowired
    private OaSysDictMapper oaSysDictMapper;

    @Autowired
    private OaOrderOtherPriceMapper oaOrderOtherPriceMapper;

    @Autowired
    private OaSysAreaMapper oaSysAreaMapper;

    @Autowired
    private OaDOrderMapper oaDOrderMapper;

    @Autowired
    private OaSysCommentMapper oaSysCommentMapper;

    @Autowired
    private OaOrderEvaluationMapper oaOrderEvaluationMapper;

    @Autowired
    private OaDVehicleGpsHistoryMapper oaDVehicleGpsHistoryMapper;

    @Autowired
    private OaOrderFeeRecordMapper oaOrderFeeRecordMapper;

    @Autowired
    private OaSysBillRulesMapper oaSysBillRulesMapper;

    @Autowired
    private DriverTripRecordMapper driverTripRecordMapper;

    @Autowired
    private CmsOrderInfoExportServer cmsOrderInfoExportServer;

    @Autowired
    private OaSysUserMapper oaSysUserMapper;

    @Autowired
    private OaSysOrderDetailsMapper oaSysOrderDetailsMapper;

    @Autowired
    private OaDOrderCharteredDetailMapper oaDOrderCharteredDetailMapper;

    @Autowired
    private OaSysOfficeMapper oaSysOfficeMapper;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private MqOrderProducer producer;

    @Autowired
    private RedisCommon redisCommon;
    private static String callbackUrl;

    @Value("${global.xc.callback}")
    public void setCallBack(String callback) {
        callbackUrl = callback;
    }

    public static String serviceId;

    @Value("${global.amap.lyServiceId}")
    public void setServiceId(String amapServiceId) {
        serviceId = amapServiceId;
    }

    //携程密钥
    @Value("${global.xc.secretKey}")
    private String secretKey;
    //供应商ID
    @Value("${global.xc.venderId}")
    private String venderId;
    //渠道
    @Value("${global.xc.channel}")
    private String channel;
    //版本
    @Value("${global.xc.version}")
    private String version;
    @Value("${global.xc.callback}")
    private String callback;

    private static final int CORE_POOL_SIZE = 6;
    private static final int MAX_POOL_SIZE = 10;
    private static final int QUEUE_CAPACITY = 200;
    private static final Long KEEP_ALIVE_TIME = 1L;
    //使用阿里巴巴推荐的创建线程池的方式
    //通过ThreadPoolExecutor构造函数自定义参数创建
    ThreadPoolExecutor executor = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAX_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(QUEUE_CAPACITY),
            new ThreadPoolExecutor.CallerRunsPolicy());


    /**
     * 查询包车等待应答的订单
     *
     * @return
     */
    @Override
    public Rv getNewCharterOrderList() {
        Integer tempListSize = oaDOrderMapper.selectCharterOrderList();
        return Rv.wrap(tempListSize);
    }

    /**
     * 导出包车订单
     *
     * @param orderList
     * @return
     */
    @Override
    public Rv exportExcelOfCharterOrder(OrderList orderList) {
        long userId = TokenUtil.getTokenUserId();
        Long officeId = orderList.getOfficeId();
        List<Long> offices = iOaSysGetOfficeIdListService.selectOfficeIdList(userId);
        if (officeId != null) {
            if (offices.contains(officeId)) {
                offices = new ArrayList<>();
                offices.add(officeId);
            } else {
                return Rv.error(EErrorCode.authErr);
            }
        }

        try {
            LinkedHashSet<Long> hashSet = new LinkedHashSet<>(offices);
            offices = new ArrayList<>(hashSet);
            List<Date> timeList = orderList.getTimeList();
            if (CheckUtil.objIsNotEmpty(timeList)) {
                if (timeList.size() == 2) {
                    if (CheckUtil.objIsNotEmpty(timeList.get(1))) {
                        orderList.setOrderEndTime(timeList.get(1));
                    }
                    if (CheckUtil.objIsNotEmpty(timeList.get(0))) {
                        orderList.setOrderStartTime(timeList.get(0));
                    }
                } else {
                    throw PangException.create(EErrorCode.missingArg);
                }
            }
            List<String> dUsedIdDriverPhoneORDriverName = this.dUsedIdDriverPhoneORDriverName(orderList);
            if (CheckUtil.objIsNotEmpty(dUsedIdDriverPhoneORDriverName)) {
                orderList.setDirverIds(dUsedIdDriverPhoneORDriverName);
            }
            List<String> vehicleIdVehNo = this.vehicleIdVehNo(orderList);
            if (CheckUtil.objIsNotEmpty(vehicleIdVehNo)) {
                orderList.setVehicleIds(vehicleIdVehNo);
            }
            List<OrderList> resultOrderLists = oaSysOrderDetailsMapper.selectCharterInfoToExport(orderList, offices);
            return Rv.wrap(resultOrderLists);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Rv.wrap();
    }

    @Override
    public Rv getOaDCharterOrderDetail(CmsOadOrderPersonalParam cmsOadOrderPersonalParam) {
        Long personalId = cmsOadOrderPersonalParam.getPersonalId();
        if (CheckUtil.objIsEmpty(personalId)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        //通过订单号查询司机接单订单详情
        OaCOrderPersonal oadOrder = getOrderByOrderNo(personalId);
        if (CheckUtil.objIsEmpty(oadOrder)) {
            throw PangException.create(EErrorCode.noData);
        }
        Long driverId = oadOrder.getDriverId();
        String orderNo = oadOrder.getOrderNo();
        if (CheckUtil.objIsEmpty(orderNo)) {
            throw PangException.create(EErrorCode.noData);
        }
        //从order-personal表查询订单信息
        CmsOadCharterOrderDetailRes result = oacOrderPersonalMapper.selectOaCorderDetailByOrderNo(orderNo);
        //根据订单号查询每天包车信息
        List<OaDOrderCharteredDetailRes> oaDOrderCharteredDetailRes = oaDOrderCharteredDetailMapper.selectCharterDetailByOrderNo(orderNo);
        //根据track_id获取轨迹
        if (CheckUtil.objIsNotEmpty(oaDOrderCharteredDetailRes)) {
            for (OaDOrderCharteredDetailRes charteredDetailRes : oaDOrderCharteredDetailRes) {
                if (CheckUtil.objIsNotEmpty(charteredDetailRes.getDriverId())) {
                    QueryWrapper<OaDUserInfo> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq(OaDUserInfo.DRIVER_ID, charteredDetailRes.getDriverId());
                    OaDUserInfo oaDUserInfo = oaDUserInfoMapper.selectOne(queryWrapper);
                    if (CheckUtil.objIsEmpty(oaDUserInfo)) {
                        return Rv.wrap(result);
                    }
                    if (CheckUtil.allObjIsEmpty(charteredDetailRes.getTrackId(), oaDUserInfo.getTid())) {
                        Long terminalId = oaDUserInfo.getTid();
                        Long trackId = charteredDetailRes.getTrackId().longValue();
                        GouldHistoryGps gouldHistoryGps = GouldMapUtils.historyGps(Long.parseLong(serviceId), trackId, terminalId, 1);
                        if (gouldHistoryGps.getErrcode() == 10000) {
                            charteredDetailRes.setGpsList(getData(gouldHistoryGps));
                        }
                    }
                }
            }
            result.setOaDOrderCharteredDetailRes(oaDOrderCharteredDetailRes);
        }
        return Rv.wrap(result);
    }


    /**
     * 根据driverIds查询包车订单匹配的运力信息
     *
     * @param driverIds
     * @return
     */
    @Override
    public Rv getCmsOaSysOrdersList(List<Long> driverIds) {
        ArrayList<DriverUserInfo> driverUserInfos = new ArrayList<>();
        for (int i = 0; i < driverIds.size(); i++) {
            DriverUserInfo driverDetails = oadUserMapper.getDriverDetails(driverIds.get(i));
            driverUserInfos.add(driverDetails);
        }
        return Rv.wrap(driverUserInfos);
    }

    /**
     * 获取自费叫车订单列表
     *
     * @return
     */
    @Override
    public Rv getCmsOacOrderPersonalList(CmsOadOrderPersonalParam cmsOadOrderPersonalParam) {
        Long sysUserId = TokenUtil.getTokenUserId();
        List<String> dataScope = TokenUtil.getRoleDataScope();
        if (CheckUtil.objIsEmpty(cmsOadOrderPersonalParam.getPage()) || CheckUtil.objIsEmpty(cmsOadOrderPersonalParam.getPageSize()) || CheckUtil.objIsEmpty(sysUserId)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        // List<Long> selectOfficeIdList=iOaSysGetOfficeIdListService.selectDUserIdList(sysUserId,dataScope);
        PageVo pageVo = new PageVo();
        List<CmsOadOrderPersonalListRes> resultList = new ArrayList<>();
        pageVo.setItems(resultList);
        pageVo.setTotal(0L);
        //分页查询司机订单列表
        IPage<OaCOrderPersonal> oadOrderIpage = getOacOrderPersonalList(cmsOadOrderPersonalParam.getPassengerName(), cmsOadOrderPersonalParam.getPassengerPhone(), cmsOadOrderPersonalParam.getCityId(), cmsOadOrderPersonalParam.getDriverName(),
                cmsOadOrderPersonalParam.getDriverPhone(), cmsOadOrderPersonalParam.getIsRefund(), cmsOadOrderPersonalParam.getStartAddress(), cmsOadOrderPersonalParam.getEndAddress(), cmsOadOrderPersonalParam.getIsChangePrice(), cmsOadOrderPersonalParam.getOrderChannel(),
                cmsOadOrderPersonalParam.getCancelReason(), cmsOadOrderPersonalParam.getBusinessType(), cmsOadOrderPersonalParam.getVehNo(), cmsOadOrderPersonalParam.getOrderStatus(), cmsOadOrderPersonalParam.getOrderNo(), cmsOadOrderPersonalParam.getOrderStartTime(),
                cmsOadOrderPersonalParam.getOrderEndTime(), cmsOadOrderPersonalParam.getPage(), cmsOadOrderPersonalParam.getPageSize());
        if (CheckUtil.objIsEmpty(oadOrderIpage) || CheckUtil.objIsEmpty(oadOrderIpage.getRecords())) {
            return Rv.wrap(pageVo);
        }
        List<Long> dIdList = new ArrayList<>();
        List<Long> vehIdList = new ArrayList<>();
        List<String> orderNoList = new ArrayList<>();
        for (OaCOrderPersonal oadOrder : oadOrderIpage.getRecords()) {
            dIdList.add(oadOrder.getDriverId());
            vehIdList.add(oadOrder.getVehicleId());
            orderNoList.add(oadOrder.getOrderNo());
        }
        //查询车辆信息
        List<OaSysVehicle> vehicleList = getVehicleListByVehId(vehIdList);
        //查询司机信息
        List<OaDUser> userList = getDriverListByIdList(dIdList);
        List<OaSysArea> oaSysAreaList = oaSysAreaMapper.selectList(null);
        List<OaSysDict> dictLevelList = getRequireLevel();
        List<OaOrderOtherPrice> priceList = getOtherPriceByOrderNoList(orderNoList);
        // 处理数据
        processData(resultList, oadOrderIpage.getRecords(), userList, vehicleList, oaSysAreaList, dictLevelList, priceList);
        pageVo.setItems(resultList);
        pageVo.setTotal(oadOrderIpage.getTotal());
        return Rv.wrap(pageVo);
    }

    /**
     * 通过司机id查询司机信息
     *
     * @param idList
     * @return
     */
    private List<OaDUser> getDriverListByIdList(List<Long> idList) {
        List<OaDUser> list = new ArrayList<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in(OaDUser.DRIVER_ID, idList);
        queryWrapper.eq(OaDUser.TAG, TokenUtil.getTag());
        list = oadUserMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * 查询评价信息
     *
     * @return
     */
    private List<OaSysComment> getCommentList() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaSysComment.TAG, TokenUtil.getTag());
        List<OaSysComment> oacUsers = oaSysCommentMapper.selectList(queryWrapper);
        return oacUsers;
    }

    /**
     * 通过车牌号查询车辆id
     *
     * @param vehIdList
     * @return
     */
    private List<OaSysVehicle> getVehicleListByVehId(List<Long> vehIdList) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in(OaSysVehicle.VEHICLE_ID, vehIdList);
        queryWrapper.eq(OaSysVehicle.TAG, TokenUtil.getTag());
        queryWrapper.orderByDesc(OaSysVehicle.CREATE_TIME);
        List<OaSysVehicle> list = oaSysVehicleMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * 查询自费叫车订单列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    private IPage<OaCOrderPersonal> getOacOrderPersonalList(String passengerName, String passengerPhone, Long cityId, String driverName, String driverPhone,
                                                            Integer isRefund, String startAddress, String endAddress, Integer isChangePrice, Integer orderChannel,
                                                            String cancelReason, Integer businessType, String vehNo, Integer status, String orderNo, Date orderStartTime, Date orderEndTime, Integer page, Integer pageSize) {
        IPage<OaCOrderPersonal> oadOrderIpage = null;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc(OaCOrderPersonal.CREATE_TIME);
        queryWrapper.eq(OaCOrderPersonal.TAG, TokenUtil.getTag());
        if (CheckUtil.objIsNotEmpty(isChangePrice)) {
            queryWrapper.eq(OaCOrderPersonal.IS_CHANGE_PRICE, isChangePrice);
        }
        if (CheckUtil.objIsNotEmpty(orderChannel)) {
            queryWrapper.eq(OaCOrderPersonal.ORDER_CHANNEL, orderChannel);
        }
        if (CheckUtil.objIsNotEmpty(cancelReason)) {
            queryWrapper.eq(OaCOrderPersonal.CANCEL_REASON, cancelReason);
        }
        if (CheckUtil.objIsNotEmpty(businessType)) {
            queryWrapper.eq(OaCOrderPersonal.VEHICLE_TYPE, businessType);
        }
        if (CheckUtil.objIsNotEmpty(cityId)) {
            queryWrapper.eq(OaCOrderPersonal.CITY_ID, cityId);
        }
        if (CheckUtil.objIsNotEmpty(orderStartTime)) {
            queryWrapper.ge(OaCOrderPersonal.ORDER_TIME, orderStartTime);
        }
        if (CheckUtil.objIsNotEmpty(orderEndTime)) {
            queryWrapper.le(OaCOrderPersonal.ORDER_TIME, orderEndTime);
        }
        if (CheckUtil.objIsNotEmpty(passengerName)) {
            queryWrapper.like(OaCOrderPersonal.PASSENGER_NAME, passengerName);
        }
        if (CheckUtil.objIsNotEmpty(passengerPhone)) {
            queryWrapper.like(OaCOrderPersonal.PASSENGER_PHONE, passengerPhone);
        }
        if (CheckUtil.objIsNotEmpty(driverName) || CheckUtil.objIsNotEmpty(driverPhone)) {
            List<OaDUser> driveList = getOaDuserListByDriverName(driverName, driverPhone);
            if (!CheckUtil.objIsEmpty(driveList)) {
                List<Long> userIdList = new ArrayList<>();
                for (OaDUser u : driveList) {
                    userIdList.add(u.getDriverId());
                }
                queryWrapper.in(OaCOrderPersonal.DRIVER_ID, userIdList);
            } else {
                return oadOrderIpage;
            }
        }
        if (CheckUtil.objIsNotEmpty(isRefund)) {
            queryWrapper.eq(OaCOrderPersonal.IS_REFUND, isRefund);
        }
        if (CheckUtil.objIsNotEmpty(startAddress)) {
            queryWrapper.like(OaCOrderPersonal.START_ADDRESS, startAddress);
        }
        if (CheckUtil.objIsNotEmpty(endAddress)) {
            queryWrapper.like(OaCOrderPersonal.END_ADDRESS, endAddress);
        }
        if (CheckUtil.objIsNotEmpty(vehNo)) {
            List<OaSysVehicle> vehList = getVehicleListByVehNo(vehNo);
            if (!CheckUtil.objIsEmpty(vehList)) {
                List<Long> vehIdList = new ArrayList<>();
                for (OaSysVehicle v : vehList) {
                    vehIdList.add(v.getVehicleId());
                }
                queryWrapper.in(OaCOrderPersonal.VEHICLE_ID, vehIdList);
            } else {
                return oadOrderIpage;
            }
        }
        if (CheckUtil.objIsNotEmpty(orderNo)) {
            queryWrapper.like(OaCOrderPersonal.ORDER_NO, orderNo);
        }
        if (CheckUtil.objIsNotEmpty(status)) {
            queryWrapper.eq(OaCOrderPersonal.ORDER_STATUS, status);
        }
        IPage<OaCOrderPersonal> iPage = new Page<>();
        iPage.setCurrent(page);
        iPage.setSize(pageSize);
        IPage<OaCOrderPersonal> list = oacOrderPersonalMapper.selectPage(iPage, queryWrapper);
        return list;
    }

    /**
     * 通过id查询车辆信息
     *
     * @param vehNo
     * @return
     */
    private List<OaSysVehicle> getVehicleListByVehNo(String vehNo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc(OaSysVehicle.CREATE_TIME);
        queryWrapper.eq(OaSysVehicle.TAG, TokenUtil.getTag());
        queryWrapper.like(OaSysVehicle.VEH_NO, vehNo);
        List<OaSysVehicle> list = oaSysVehicleMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * 通过司机姓名查询司机辆id
     *
     * @param driverName
     * @return
     */
    private List<OaDUser> getOaDuserListByDriverName(String driverName, String driverPhone) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc(OaDUser.CREATE_TIME);
        queryWrapper.eq(OaDUser.TAG, TokenUtil.getTag());
        if (CheckUtil.objIsNotEmpty(driverName)) {
            queryWrapper.like(OaDUser.DRIVER_NAME, driverName);
        }
        if (CheckUtil.objIsNotEmpty(driverPhone)) {
            queryWrapper.like(OaDUser.DRIVER_PHONE, driverPhone);
        }
        List<OaDUser> list = oadUserMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * 获取自费叫车订单详情
     *
     * @param cmsOadOrderPersonalParam
     * @return
     */
    @Override
    public Rv getCmsOacOrderPersonalDetail(CmsOadOrderPersonalParam cmsOadOrderPersonalParam) {
        Long personalId = cmsOadOrderPersonalParam.getPersonalId();
        if (CheckUtil.objIsEmpty(personalId)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        //通过订单号查询司机接单订单详情
        OaCOrderPersonal oadOrder = getOrderByOrderNo(personalId);
        Long driverId = oadOrder.getDriverId();
        String orderNo = oadOrder.getOrderNo();
        if (CheckUtil.objIsEmpty(oadOrder)) {
            throw PangException.create(EErrorCode.noData);
        }
        //设置返回结果
        CmsOadOrderPersonalDetailRes result = new CmsOadOrderPersonalDetailRes();
        result.setCreateTimeStr(new DateToStringConverter().convert(oadOrder.getCreateTime()));
        result.setEstimateDistance("");
        if (CheckUtil.objIsNotEmpty(oadOrder.getEstimateDistance())) {
            result.setEstimateDistance(String.valueOf(oadOrder.getEstimateDistance()) + MessageConstant.KILOMETRE);
        }
        result.setPassengerName(oadOrder.getPassengerName());
        result.setPersonalId(oadOrder.getPersonalId());
        result.setCarpoolNumber(oadOrder.getCarpoolNumber());
        result.setOrderType(ECallVehType.finaByValue(oadOrder.getOrderType()));
        result.setOrderTime(new DateToStringConverter().convert(oadOrder.getOrderTime()));
        result.setArriveTime(new DateToStringConverter().convert(oadOrder.getArriveTime()));
        result.setAppointment(new DateToStringConverter().convert(oadOrder.getAppointment()));
        result.setCarpoolSerialNo(oadOrder.getCarpoolSerialNo());
        result.setOrderNo(oadOrder.getOrderNo());
        result.setOrderStatus(EOrderStatus.findById(oadOrder.getOrderStatus()).getValue());
        result.setPassengerPhone(oadOrder.getPassengerPhone());
        result.setTotalFee(oadOrder.getTotalFee());
        result.setNotarizeTime(new DateToStringConverter().convert(oadOrder.getNotarizeTime()));
        result.setMeetPassengerTimeStr(new DateToStringConverter().convert(oadOrder.getMeetPassengerTime()));
        result.setMilageDistance(oadOrder.getMilageDistance());
        result.setDurationTime(oadOrder.getDurationTime());
        if (CheckUtil.objIsNotEmpty(oadOrder.getPaymentType())) {
            result.setPaymentType(EPayType.findById(oadOrder.getPaymentType()).getValue());
        }
        result.setCarpoolNumber(oadOrder.getCarpoolNumber());
        result.setCarpoolSerialNo(oadOrder.getCarpoolSerialNo());
        if (CheckUtil.objIsNotEmpty(oadOrder.getInvoiceStatus())) {
            result.setInvoiceStatus(EInvoiceType.findById(oadOrder.getInvoiceStatus()).getValue());
        }
        OaDUser user = oadUserMapper.selectById(oadOrder.getDriverId());
        //查询司机信息
        if (CheckUtil.objIsNotEmpty(user)) {
            result.setDriverName(user.getDriverName());
            result.setDriverPhone(user.getDriverPhone());
        }
        OaCUser cuser = oacUserMapper.selectById(oadOrder.getUserId());
        //查询用户信息
        if (CheckUtil.objIsNotEmpty(cuser)) {
            result.setUserName(cuser.getUserName());
        }
        result.setIsCarpool(EEvaluationIsShow.findById(oadOrder.getIsCarpool()).getDesc());
        if (CheckUtil.objIsNotEmpty(oadOrder.getIsComment())) {
            result.setIsComment(EEvaluationIsShow.findById(oadOrder.getIsComment()).getDesc());
        }
        //查询车辆信息
        OaSysVehicle vehicle = oaSysVehicleMapper.selectById(oadOrder.getVehicleId());
        if (CheckUtil.objIsNotEmpty(vehicle)) {
            result.setVehicleNo(vehicle.getVehNo());
        }
        // 数据整理
        dataReduction(result, oadOrder);
        // 新增得字段
        addDataReduction(result, oadOrder);
        result.setEmptyDistance(oadOrder.getEmptyDistance());
        // 判断是否改价
        getOrderFeeRecord(result, oadOrder.getOrderNo(), oadOrder.getRulesId());
        // 评价
        if (CheckUtil.objIsNotEmpty(oadOrder.getIsComment())) {
            if (EEvaluationIsShow.findById(oadOrder.getIsComment()).getValue().equals(EEvaluationIsShow.yes.getValue())) {
                String evaluation = evaluation(oadOrder.getOrderNo(), 0);
                result.setEvaluationComment(evaluation);
            }
        }
        //查询订单的经纬度
        QueryWrapper<OaSysOrderDetails> oaDOrderQueryWrapper = new QueryWrapper<>();
        oaDOrderQueryWrapper.eq(OaSysOrderDetails.ORDER_NO, cmsOadOrderPersonalParam.getOrderNo());
        OaSysOrderDetails oaDOrder = oaSysOrderDetailsMapper.selectOne(oaDOrderQueryWrapper);

        //出发地经纬度
        if (CheckUtil.objIsNotEmpty(oadOrder.getStartLng(), oadOrder.getStartLat())) {
            result.setFlng(oadOrder.getStartLng());
            result.setFlat(oadOrder.getStartLat());
        }
        //目的地经纬度
        if (CheckUtil.objIsNotEmpty(oadOrder.getEndLng(), oadOrder.getEndLat())) {
            result.setTlng(oadOrder.getEndLng());
            result.setTlat(oadOrder.getEndLat());
        }
        if (CheckUtil.objIsNotEmpty(oaDOrder)) {
            //开始行程经纬度
            if (CheckUtil.objIsNotEmpty(oaDOrder.getStartJourneyLng(), oaDOrder.getStartJourneyLat())) {
                result.setActualFlng(oaDOrder.getStartJourneyLng());
                result.setActualFlat(oaDOrder.getStartJourneyLat());
            }
            //行程结束经纬度
            if (CheckUtil.objIsNotEmpty(oaDOrder.getEndJourneyLng(), oaDOrder.getEndJourneyLat())) {
                result.setActualTlng(oaDOrder.getEndJourneyLng());
                result.setActualTlat(oaDOrder.getEndJourneyLat());
            }
            //司机起点位置经纬度
            if (CheckUtil.objIsNotEmpty(oaDOrder.getMeetCStartLng(), oaDOrder.getMeetCStartLat())) {
                result.setMeetCStartFlng(oaDOrder.getMeetCStartLng());
                result.setMeetCStartTlat(oaDOrder.getMeetCStartLat());
            }
            //司机已就位位置
            if (CheckUtil.objIsNotEmpty(oaDOrder.getDriverInPlaceStartLat(), oaDOrder.getDriverInPlaceStartLng())) {
                result.setArriveReservationFlng(oaDOrder.getDriverInPlaceStartLng());
                result.setArriveReservationFlat(oaDOrder.getDriverInPlaceStartLat());
            }
        }
        //查询点位数据
        QueryWrapper<OaDUserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaDUserInfo.DRIVER_ID, driverId);
        OaDUserInfo oaDUserInfo = oaDUserInfoMapper.selectOne(queryWrapper);
        if (CheckUtil.objIsEmpty(oaDUserInfo)) {
            return Rv.wrap(result);
        }
        Long terminalId = oaDUserInfo.getTid();
        QueryWrapper<OaDOrder> oaCOrderPersonalQueryWrapper = new QueryWrapper<>();
        oaCOrderPersonalQueryWrapper.eq(OaDOrder.ORDER_NO, orderNo);
        OaDOrder oaDOrder1 = oaDOrderMapper.selectOne(oaCOrderPersonalQueryWrapper);
        if (CheckUtil.objIsNotEmpty(oaDOrder1)) {
            String trackId = oaDOrder1.getTrackId();
            if (CheckUtil.strIsNotEmpty(trackId)) {
                String[] tids = trackId.split(",");
                Long tid1 = Long.parseLong(tids[0]);
                Long tid2 = Long.parseLong(tids[1]);
                if (tid1 != null) {
                    GouldHistoryGps gouldHistoryGps = GouldMapUtils.historyGps(Long.parseLong(serviceId), tid1, terminalId, 1);
                    if (gouldHistoryGps.getErrcode() == 10000) {
                        result.setGpsList1(getData(gouldHistoryGps));
                    }
                }
                if (tid2 != null) {
                    GouldHistoryGps gouldHistoryGps = GouldMapUtils.historyGps(Long.parseLong(serviceId), tid2, terminalId, 1);
                    if (gouldHistoryGps.getErrcode() == 10000) {
                        result.setGpsList2(getData(gouldHistoryGps));
                    }
                }
            }
        }
        return Rv.wrap(result);
    }

    static List<List<Double>> getData(GouldHistoryGps gouldHistoryGps) {
        if (gouldHistoryGps == null || gouldHistoryGps.getData() == null) {
            return null;
        }
        List<GouldHistoryGps.DataBean.TracksBean> tracks = gouldHistoryGps.getData().getTracks();
        List<List<Double>> reListing = new ArrayList<>();
        ;
        for (int i = 0; i < tracks.size(); i++) {
            List<GouldHistoryGps.DataBean.TracksBean.Point> points = tracks.get(i).getPoints();
            for (int j = 0; j < points.size(); j++) {
                String location = points.get(j).getLocation();
                String[] locations = location.split(",");
                List<Double> pointList = new ArrayList<>();
                pointList.add(Double.parseDouble(locations[0]));
                pointList.add(Double.parseDouble(locations[1]));
                reListing.add(pointList);
            }
        }
        return reListing;
    }

    @Autowired
    private OaDUserInfoMapper oaDUserInfoMapper;

    /**
     * 获取订单详细信息
     *
     * @param orderNo
     * @return
     */
    @Override
    public Rv getOrderDetail(String orderNo) {
        if (CheckUtil.objIsEmpty(orderNo)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        QueryWrapper<OaSysOrderDetails> oaSysOrderDetailsQueryWrapper = new QueryWrapper<>();
        oaSysOrderDetailsQueryWrapper.eq(OaSysOrderDetails.ORDER_NO, orderNo);
        OaSysOrderDetails oaSysOrderDetails = oaSysOrderDetailsMapper.selectOne(oaSysOrderDetailsQueryWrapper);
        if (CheckUtil.objIsEmpty(oaSysOrderDetails)) {
            throw PangException.create(EErrorCode.unData);
        }
        return Rv.wrap(oaSysOrderDetails);
    }

    /**
     * 数据整理
     *
     * @param result
     * @param oadOrder
     * @return
     */
    public CmsOadOrderPersonalDetailRes dataReduction(CmsOadOrderPersonalDetailRes result, OaCOrderPersonal oadOrder) {
        result.setDrawFee(new BigDecimal(0));
        result.setCouponDeductionFee(new BigDecimal(0));
        result.setActualFee(new BigDecimal(0));
        result.setServiceFee(new BigDecimal(0));
        result.setAwaitFee(new BigDecimal(0));
        result.setEmptyDrivingFee(new BigDecimal(0));
        if (CheckUtil.objIsNotEmpty(oadOrder.getServiceFee())) {
            result.setServiceFee(oadOrder.getServiceFee());
        }
        if (CheckUtil.objIsNotEmpty(oadOrder.getAwaitFee())) {
            result.setAwaitFee(oadOrder.getAwaitFee());
        }
        if (CheckUtil.objIsNotEmpty(oadOrder.getEmptyDrivingFee())) {
            result.setEmptyDrivingFee(oadOrder.getEmptyDrivingFee());
        }
        result.setStartFee(oadOrder.getStartFee());
        result.setStartFeeStr("");
        if (CheckUtil.objIsNotEmpty(oadOrder.getStartFee())) {
            result.setStartFeeStr(oadOrder.getStartFee() + MessageConstant.MONEY_NAME);
        }
        result.setEstimatePrice("");
        if (CheckUtil.strIsNotEmpty(oadOrder.getEstimatePrice())) {
            result.setEstimatePrice(oadOrder.getEstimatePrice() + MessageConstant.MONEY_NAME);
        }
        result.setBaseFee(oadOrder.getBaseFee());
        result.setDistanceFee(oadOrder.getDistanceFee());
        if (CheckUtil.objIsNotEmpty(oadOrder.getActualFee())) {
            result.setActualFee(oadOrder.getActualFee());
        }
        result.setDurationFee(oadOrder.getDurationFee());
        result.setMileageFee(oadOrder.getMileageFee());
        if (CheckUtil.objIsNotEmpty(oadOrder.getCouponDeductionFee())) {
            result.setCouponDeductionFee(oadOrder.getCouponDeductionFee());
        }
        result.setHighSpeedFee(new BigDecimal(0));
        result.setParkFee(new BigDecimal(0));
        result.setCrossBridgeFee(new BigDecimal(0));
        result.setOtherFee(new BigDecimal(0));
        //通过订单号查询其他费用信息
        List<OaOrderOtherPrice> priceList = getOtherPriceByOrderNo(oadOrder.getOrderNo());
        if (!priceList.isEmpty()) {
            for (OaOrderOtherPrice price : priceList) {
                if (price.getCostType().equals(EOrderOtherPrice.bridgeToll.getType())) {
                    result.setCrossBridgeFee(price.getCostAmount());
                }
                if (price.getCostType().equals(EOrderOtherPrice.highSpeedFee.getType())) {
                    result.setHighSpeedFee(price.getCostAmount());
                }
                if (price.getCostType().equals(EOrderOtherPrice.parkingFee.getType())) {
                    result.setParkFee(price.getCostAmount());
                }
                if (price.getCostType().equals(EOrderOtherPrice.otherFee.getType())) {
                    result.setOtherFee(price.getCostAmount());
                }
            }
        }
        String province = "";
        result.setCityName("");
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaSysArea.AD_CODE, oadOrder.getCityId());
        List<OaSysArea> areaList = oaSysAreaMapper.selectList(queryWrapper);
        if (!areaList.isEmpty()) {
            result.setCityName(areaList.get(0).getName());
            OaSysArea provinceArea = oaSysAreaMapper.selectById(areaList.get(0).getParentId());
            province = provinceArea.getName();
        }
        if (CheckUtil.objIsNotEmpty(oadOrder.getDrawFee())) {
            result.setDrawFee(oadOrder.getDrawFee());
        }
        result.setStartAddress(oadOrder.getStartAddress());
        result.setEndAddress(oadOrder.getEndAddress());
        if (StringUtils.isNotBlank(province)) {
            if (StringUtils.isNotBlank(oadOrder.getStartAddress()) && oadOrder.getStartAddress().indexOf(province) == 0) {
                result.setStartAddress(StringUtils.substringAfter(oadOrder.getStartAddress(), province));
            }
            if (StringUtils.isNotBlank(oadOrder.getEndAddress()) && oadOrder.getEndAddress().indexOf(province) == 0) {
                result.setEndAddress(StringUtils.substringAfter(oadOrder.getEndAddress(), province));
            }
        }
        if (StringUtils.isNotEmpty(result.getCityName())) {
            if (StringUtils.isNotBlank(result.getStartAddress()) && result.getStartAddress().indexOf(result.getCityName()) == 0) {
                result.setStartAddress(StringUtils.substringAfter(result.getStartAddress(), result.getCityName()));
            }
            if (StringUtils.isNotBlank(result.getEndAddress()) && result.getEndAddress().indexOf(result.getCityName()) == 0) {
                result.setEndAddress(StringUtils.substringAfter(result.getEndAddress(), result.getCityName()));
            }
        }
        // 查询司机订单
        OaDOrder dOrder = oaDOrderMapper.selectById(oadOrder.getOrderNo());
        if (CheckUtil.objIsNotEmpty(dOrder)) {
            result.setBeginChargeTime(new DateToStringConverter().convert(dOrder.getBeginChargeTime()));
            result.setFinishTime(new DateToStringConverter().convert(dOrder.getFinishTime()));
            result.setDepartureTime(new DateToStringConverter().convert(dOrder.getDepartureTime()));
            result.setActualStartName(dOrder.getActualStartName());
            result.setActualEndName(dOrder.getActualEndName());
            if (CheckUtil.objIsNotEmpty(dOrder.getIsComment())) {
                result.setDriverIsCommentStr(EEvaluationIsShow.findById(dOrder.getIsComment()).getDesc());
                if (EEvaluationIsShow.findById(dOrder.getIsComment()).getValue() == 1) {
                    String evaluation = evaluation(dOrder.getOrderNo(), 1);
                    result.setDriverEvaluationComment(evaluation);
                }
            }
            result.setDriverStartSite(dOrder.getPickPassengersAddress());
            result.setDriverStartAddress(dOrder.getActualStartName());
            result.setDriverEndAddress(dOrder.getActualEndName());
            if (StringUtils.isNotBlank(province)) {
                if (StringUtils.isNotBlank(dOrder.getPickPassengersAddress()) && dOrder.getPickPassengersAddress().indexOf(province) == 0) {
                    result.setDriverStartSite(StringUtils.substringAfter(dOrder.getPickPassengersAddress(), province));
                }
                if (StringUtils.isNotBlank(dOrder.getActualStartName()) && dOrder.getActualStartName().indexOf(province) == 0) {
                    result.setDriverStartAddress(StringUtils.substringAfter(dOrder.getActualStartName(), province));
                }
                if (StringUtils.isNotBlank(dOrder.getActualEndName()) && dOrder.getActualEndName().indexOf(province) == 0) {
                    result.setDriverEndAddress(StringUtils.substringAfter(dOrder.getActualEndName(), province));
                }
            }
            if (StringUtils.isNotEmpty(result.getCityName())) {
                if (StringUtils.isNotBlank(result.getDriverStartSite()) && result.getDriverStartSite().indexOf(result.getCityName()) == 0) {
                    result.setDriverStartSite(StringUtils.substringAfter(result.getDriverStartSite(), result.getCityName()));
                }
                if (StringUtils.isNotBlank(result.getDriverStartAddress()) && result.getDriverStartAddress().indexOf(result.getCityName()) == 0) {
                    result.setDriverStartAddress(StringUtils.substringAfter(result.getDriverStartAddress(), result.getCityName()));
                }
                if (StringUtils.isNotBlank(result.getDriverEndAddress()) && result.getDriverEndAddress().indexOf(result.getCityName()) == 0) {
                    result.setDriverEndAddress(StringUtils.substringAfter(result.getDriverEndAddress(), result.getCityName()));
                }
            }


        }
        return result;
    }

    /**
     * 数据整理
     *
     * @param result
     * @param oaDOrder
     * @return
     */
    public CmsOadOrderPersonalDetailRes addDataReduction(CmsOadOrderPersonalDetailRes result, OaCOrderPersonal oaDOrder) {
        List<OaOrderOtherPrice> priceList = getOtherPriceByOrderNo(oaDOrder.getOrderNo());
        BigDecimal zero = new BigDecimal(0);
        if (CheckUtil.objIsNotEmpty(oaDOrder.getCancelReason())) {
            //result.setCancelReasonStr(ECancelOrderType.finaByType(oaDOrder.getCancelReason()).getValue());
            result.setCancelReasonStr(com.xnyzc.lhy.mis.entity.common.penum.
                    ECancelOrderType.finaByType(oaDOrder.getCancelReason()).getValue());
        }
        result.setDidiOrderId(oaDOrder.getDidiOrderId());
        result.setTripFee(zero);
        result.setCityName("");
        if (CheckUtil.objIsNotEmpty(oaDOrder.getStartFee(), oaDOrder.getMileageFee(), oaDOrder.getDurationFee(), oaDOrder.getDistanceFee())) {
            result.setTripFee(oaDOrder.getStartFee().add(oaDOrder.getMileageFee()).add(oaDOrder.getDurationFee()).add(oaDOrder.getDistanceFee()));
        }
        BigDecimal additionFee = new BigDecimal(0);
        if (!priceList.isEmpty()) {
            for (OaOrderOtherPrice price : priceList) {
                if (oaDOrder.getOrderNo().equals(price.getOrderNo())) {
                    additionFee = additionFee.add(price.getCostAmount());
                }
            }
        }
        result.setAdditionFee(additionFee);
        result.setOrderTime(new DateToStringConverter().convert(oaDOrder.getOrderTime()));
        result.setBusinessTypeStr(EBusinessType.findById(Integer.valueOf(oaDOrder.getBusinessType())).getValue());
        result.setVehicleTypeStr(EVehicleType.findVehType(oaDOrder.getVehicleType()).getDesc());
        result.setEstimateTimeStr("");
        if (CheckUtil.objIsNotEmpty(oaDOrder.getEstimateTime())) {
            result.setEstimateTimeStr(oaDOrder.getEstimateTime() + MessageConstant.MINUTES);
        }
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq(OaDOrder.ORDER_NO, oaDOrder.getOrderNo());
//        List<OaDOrder> dOrderList = oaDOrderMapper.selectList(queryWrapper);
//        if (!dOrderList.isEmpty()) {
//            result.setMeetPassengerTimeStr(new DateToStringConverter().convert(dOrderList.get(0).getDepartureTime()));
//        }
        result.setMeetPassengerTimeStr(new DateToStringConverter().convert(oaDOrder.getMeetPassengerTime()));
        result.setArriveMeetPassengerTimeStr(new DateToStringConverter().convert(oaDOrder.getArriveMeetPassengerTime()));
        result.setNotarizeTimeStr(new DateToStringConverter().convert(oaDOrder.getNotarizeTime()));
        result.setArriveTimeStr(new DateToStringConverter().convert(oaDOrder.getArriveTime()));
        result.setPassengerPayTimeStr(new DateToStringConverter().convert(oaDOrder.getPassengerPayTime()));
        result.setCancelOrderTimeStr(new DateToStringConverter().convert(oaDOrder.getCancelOrderTime()));
        return result;
    }

    /**
     * 订单改价修改
     *
     * @param result
     * @param orderNo
     * @return
     */
    public CmsOadOrderPersonalDetailRes getOrderFeeRecord(CmsOadOrderPersonalDetailRes result, String orderNo, Long rulesId) {
        result.setStartMileage(0);
        result.setStartTime(0);
        result.setTravelMileage(result.getMilageDistance());
        result.setTravelTimeStr("");
        if (CheckUtil.objIsNotEmpty(result.getDurationTime())) {
            result.setTravelTimeStr(result.getDurationTime() + MessageConstant.MINUTES);
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaOrderFeeRecord.ORDER_NO, orderNo);
        queryWrapper.eq(OaOrderFeeRecord.UPDATE_TYPE, 0);
        List<OaOrderFeeRecord> feeRecordList = oaOrderFeeRecordMapper.selectList(queryWrapper);
        if (!feeRecordList.isEmpty()) {
            // 0 - 起步价 1 - 里程费 2 - 时长费 3 - 远途费 4 - 路桥费 5 - 停车费 6 - 高速费 7 - 其他费用 8 - 总费用
            for (OaOrderFeeRecord fee : feeRecordList) {
                if (fee.getFeeType().equals(EUpdateOrderFeeType.startFee.getType())) {
                    result.setStartFee(fee.getDiffFee());
                    break;
                } else if (fee.getFeeType().equals(EUpdateOrderFeeType.mileageFee.getType())) {
                    result.setMileageFee(fee.getDiffFee());
                    break;
                } else if (fee.getFeeType().equals(EUpdateOrderFeeType.timeFee.getType())) {
                    result.setDurationFee(fee.getDiffFee());
                    break;
                } else if (fee.getFeeType().equals(EUpdateOrderFeeType.distanceFee.getType())) {
                    result.setDistanceFee(fee.getDiffFee());
                    break;
                } else if (fee.getFeeType().equals(EUpdateOrderFeeType.bridgeFee.getType())) {
                    result.setCrossBridgeFee(fee.getDiffFee());
                    break;
                } else if (fee.getFeeType().equals(EUpdateOrderFeeType.highSpeedFee.getType())) {
                    result.setHighSpeedFee(fee.getDiffFee());
                    break;
                } else if (fee.getFeeType().equals(EUpdateOrderFeeType.parkingFee.getType())) {
                    result.setParkFee(fee.getDiffFee());
                    break;
                } else if (fee.getFeeType().equals(EUpdateOrderFeeType.otherFee.getType())) {
                    result.setOtherFee(fee.getDiffFee());
                    break;
                }
            }
        }
        result.setTripFee(result.getStartFee().add(result.getMileageFee()).add(result.getDurationFee()).add(result.getDistanceFee()));
        result.setAdditionFee(result.getCrossBridgeFee().add(result.getHighSpeedFee()).add(result.getParkFee()).add(result.getOtherFee()));
        return result;
    }

    public String evaluation(String orderNo, Integer userType) {
        String evaluationStr = "";
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaOrderEvaluation.TAG, TokenUtil.getTag());
        queryWrapper.eq(OaOrderEvaluation.ORDER_NO, orderNo);
        queryWrapper.eq(OaOrderEvaluation.USER_TYPE, userType);
        List<OaOrderEvaluation> evaluationList = oaOrderEvaluationMapper.selectList(queryWrapper);
        Map<Long, List<Long>> contentMap = new HashMap<>();
        for (OaOrderEvaluation r : evaluationList) {
            List<Long> list = new ArrayList<>();
            if (r.getTagCommentContent().contains(",")) {
                String[] str = r.getTagCommentContent().split(",");
                for (int i = 0; i < str.length; i++) {
                    list.add(Long.parseLong(str[i].trim()));
                }
            } else {
                list.add(Long.parseLong(r.getTagCommentContent().trim()));
            }
            contentMap.put(r.getEvaluationId(), list);
        }
        //查询所有的评价信息
        List<OaSysComment> commentList = getCommentList();
        if (!evaluationList.isEmpty()) {
            for (OaOrderEvaluation r : evaluationList) {
                if (CheckUtil.objIsNotEmpty(commentList)) {
                    List<Long> contIdList = contentMap.get(r.getEvaluationId());
                    StringBuffer sbf = new StringBuffer();
                    for (Long id : contIdList) {
                        sbf.append(" ");
                        for (OaSysComment c : commentList) {
                            if (id.equals(c.getCommentId())) {
                                sbf.append(c.getCommentContent() + ",");
                            }
                        }
                    }
                    evaluationStr = sbf.toString();
                }
            }
        }
        return evaluationStr;
    }

    /**
     * 通过订单号查询其他费用信息
     *
     * @param orderNo
     * @return
     */
    private List<OaOrderOtherPrice> getOtherPriceByOrderNo(String orderNo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaOrderOtherPrice.TAG, TokenUtil.getTag());
        queryWrapper.eq(OaOrderOtherPrice.ORDER_NO, orderNo);
        List<OaOrderOtherPrice> list = oaOrderOtherPriceMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * 通过订单号查询其他费用信息
     *
     * @param orderNo
     * @return
     */
    private List<OaOrderOtherPrice> getOtherPriceByOrderNoList(List<String> orderNo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaOrderOtherPrice.TAG, TokenUtil.getTag());
        queryWrapper.in(OaOrderOtherPrice.ORDER_NO, orderNo);
        List<OaOrderOtherPrice> list = oaOrderOtherPriceMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * 通过订单号查询自费叫车订单详情
     *
     * @param personalId
     * @return
     */
    private OaCOrderPersonal getOrderByOrderNo(Long personalId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        //queryWrapper.eq(OaCOrderPersonal.TAG, TokenUtil.getTag());
        queryWrapper.eq(OaCOrderPersonal.PERSONAL_ID, personalId);
        List<OaCOrderPersonal> list = oacOrderPersonalMapper.selectList(queryWrapper);
        if (CheckUtil.objIsEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 导出订单
     *
     * @return
     */
    @Override
    public Rv exportOrderExcel(CmsOadOrderPersonalParam cmsOadOrderPersonalParam) {
        Long sysUserId = TokenUtil.getTokenUserId();
        List<String> dataScope = TokenUtil.getRoleDataScope();
        if (CheckUtil.objIsEmpty(dataScope) || CheckUtil.objIsEmpty(sysUserId)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        List<Long> selectOfficeIdList = iOaSysGetOfficeIdListService.selectDUserIdList(sysUserId, dataScope);
        List<CmsOadOrderPersonalListRes> resultList = new ArrayList<>();
        //分页查询司机订单列表
        List<OaCOrderPersonal> oadOrderIpage = getExportOacOrderPersonalList(cmsOadOrderPersonalParam.getPassengerName(), cmsOadOrderPersonalParam.getPassengerPhone(), cmsOadOrderPersonalParam.getCityId(), cmsOadOrderPersonalParam.getDriverName(),
                cmsOadOrderPersonalParam.getDriverPhone(), cmsOadOrderPersonalParam.getIsRefund(), cmsOadOrderPersonalParam.getStartAddress(), cmsOadOrderPersonalParam.getEndAddress(), cmsOadOrderPersonalParam.getIsChangePrice(), cmsOadOrderPersonalParam.getOrderChannel(),
                cmsOadOrderPersonalParam.getCancelReason(), cmsOadOrderPersonalParam.getBusinessType(), cmsOadOrderPersonalParam.getVehNo(), cmsOadOrderPersonalParam.getOrderStatus(), cmsOadOrderPersonalParam.getOrderNo(), cmsOadOrderPersonalParam.getOrderStartTime(),
                cmsOadOrderPersonalParam.getOrderEndTime());
        if (CheckUtil.objIsEmpty(oadOrderIpage)) {
            return Rv.wrap(EErrorCode.success, resultList);
        }
        List<Long> dIdList = new ArrayList<>();
        List<Long> vehIdList = new ArrayList<>();
        List<String> orderNoList = new ArrayList<>();
        for (OaCOrderPersonal oadOrder : oadOrderIpage) {
            dIdList.add(oadOrder.getDriverId());
            vehIdList.add(oadOrder.getVehicleId());
            orderNoList.add(oadOrder.getOrderNo());
        }
        List<OaSysVehicle> vehicleList = getVehicleListByVehId(vehIdList);
        List<OaDUser> userList = getDriverListByIdList(dIdList);
        List<OaSysArea> oaSysAreaList = oaSysAreaMapper.selectList(null);
        List<OaSysDict> dictLevelList = getRequireLevel();
        List<OaOrderOtherPrice> priceList = getOtherPriceByOrderNoList(orderNoList);
        // 处理数据
        processData(resultList, oadOrderIpage, userList, vehicleList, oaSysAreaList, dictLevelList, priceList);
        return Rv.wrap(EErrorCode.success, resultList);
    }

    /**
     * 查询业务类型
     *
     * @return
     */
    private List<OaSysDict> getRequireLevel() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaSysDict.TYPE, "require_level");
        List<OaSysDict> dictLevelList = oaSysDictMapper.selectList(queryWrapper);
        return dictLevelList;
    }


    public List<CmsOadOrderPersonalListRes> processData(List<CmsOadOrderPersonalListRes> resultList, List<OaCOrderPersonal> oadOrderIpage, List<OaDUser> userList, List<OaSysVehicle> vehicleList, List<OaSysArea> oaSysAreaList, List<OaSysDict> dictLevelList, List<OaOrderOtherPrice> priceList) {
        CmsOadOrderPersonalListRes result = null;
        for (OaCOrderPersonal oaDOrder : oadOrderIpage) {
            BigDecimal zero = new BigDecimal(0);
            result = new CmsOadOrderPersonalListRes();
            if (CheckUtil.objIsNotEmpty(oaDOrder.getCancelReason())) {
                //result.setCancelReasonStr(ECancelOrderType.finaByType(oaDOrder.getCancelReason()).getValue());
                result.setCancelReasonStr(com.xnyzc.lhy.mis.entity.common.penum.
                        ECancelOrderType.finaByType(oaDOrder.getCancelReason()).getValue());
            }
            result.setOrderStatus(oaDOrder.getOrderStatus());
            result.setTripFee(zero);
            result.setCityName("");
            if (CheckUtil.objIsNotEmpty(oaDOrder.getStartFee(), oaDOrder.getMileageFee(), oaDOrder.getDurationFee(), oaDOrder.getDistanceFee())) {
                result.setTripFee(oaDOrder.getStartFee().add(oaDOrder.getMileageFee()).add(oaDOrder.getDurationFee()).add(oaDOrder.getDistanceFee()));
            }
            BigDecimal additionFee = new BigDecimal(0);
            if (!priceList.isEmpty()) {
                for (OaOrderOtherPrice price : priceList) {
                    if (oaDOrder.getOrderNo().equals(price.getOrderNo())) {
                        additionFee = additionFee.add(price.getCostAmount());
                    }
                }
            }
            result.setAdditionFee(additionFee);
            if (CheckUtil.objIsNotEmpty(vehicleList)) {
                for (OaSysVehicle v : vehicleList) {
                    if (v.getVehicleId().equals(oaDOrder.getVehicleId())) {
                        result.setVehNo(v.getVehNo());
                    }
                }
            }
            if (CheckUtil.objIsNotEmpty(userList)) {
                for (OaDUser user : userList) {
                    if (user.getDriverId().equals(oaDOrder.getDriverId())) {
                        result.setDriverPhone(user.getDriverPhone());
                        result.setDriverName(user.getDriverName());
                    }
                }
            }
            result.setPersonalId(oaDOrder.getPersonalId());
            result.setActualFee(oaDOrder.getActualFee());
            result.setStartAddress(oaDOrder.getStartAddress());
            result.setEndAddress(oaDOrder.getEndAddress());
            result.setTotalFee(oaDOrder.getTotalFee());
            result.setOrderTime(new DateToStringConverter().convert(oaDOrder.getOrderTime()));
            result.setOrderNo(oaDOrder.getOrderNo());
            result.setCancelOrderTime(new DateToStringConverter().convert(oaDOrder.getCancelOrderTime()));
            result.setPassengerPayTime(new DateToStringConverter().convert(oaDOrder.getPassengerPayTime()));
            result.setPassengerName(oaDOrder.getPassengerName());
            result.setPassengerPhone(oaDOrder.getPassengerPhone());
            result.setDidiOrderId(oaDOrder.getDidiOrderId());
            result.setOrderStatusStr(EOrderStatus.findById(oaDOrder.getOrderStatus()).getValue());
            result.setOrderTypeStr(ECallVehType.finaByValue(oaDOrder.getOrderType()));
            result.setMeetPassengerTime(new DateToStringConverter().convert(oaDOrder.getMeetPassengerTime()));
            result.setNotarizeTime(new DateToStringConverter().convert(oaDOrder.getNotarizeTime()));
            result.setOrderChannelStr(EOrderChannelType.findById(oaDOrder.getOrderChannel()).getValue());
            if (CheckUtil.objIsNotEmpty(oaDOrder.getCityId())) {
                for (OaSysArea area : oaSysAreaList) {
                    if (oaDOrder.getCityId().equals(area.getAdCode())) {
                        result.setCityName(area.getName());
                    }
                }
            }
            if (CheckUtil.objIsNotEmpty(oaDOrder.getVehicleType(), dictLevelList)) {
                for (OaSysDict dict : dictLevelList) {
                    if (String.valueOf(oaDOrder.getVehicleType()).equals(dict.getValue())) {
                        result.setBusinessTypeStr(dict.getLabel());
                    }
                }
            }
            resultList.add(result);
        }
        return resultList;
    }

    /**
     * 查询自费叫车订单列表
     *
     * @return
     */
    private List<OaCOrderPersonal> getExportOacOrderPersonalList(
            String passengerName, String passengerPhone, Long cityId, String driverName, String driverPhone,
            Integer isRefund, String startAddress, String endAddress, Integer isChangePrice, Integer orderChannel,
            String cancelReason, Integer businessType, String vehNo, Integer status, String orderNo, Date orderStartTime, Date orderEndTime) {
        List<OaCOrderPersonal> list = new ArrayList<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc(OaCOrderPersonal.CREATE_TIME);
        queryWrapper.eq(OaCOrderPersonal.TAG, TokenUtil.getTag());
        if (CheckUtil.objIsNotEmpty(isChangePrice)) {
            queryWrapper.eq(OaCOrderPersonal.IS_CHANGE_PRICE, isChangePrice);
        }
        if (CheckUtil.objIsNotEmpty(orderChannel)) {
            queryWrapper.eq(OaCOrderPersonal.ORDER_CHANNEL, orderChannel);
        }
        if (CheckUtil.objIsNotEmpty(cancelReason)) {
            queryWrapper.eq(OaCOrderPersonal.CANCEL_REASON, cancelReason);
        }
        if (CheckUtil.objIsNotEmpty(businessType)) {
            queryWrapper.eq(OaCOrderPersonal.VEHICLE_TYPE, businessType);
        }
        if (CheckUtil.objIsNotEmpty(cityId)) {
            queryWrapper.eq(OaCOrderPersonal.CITY_ID, cityId);
        }
        if (CheckUtil.objIsNotEmpty(orderStartTime)) {
            queryWrapper.ge(OaCOrderPersonal.ORDER_TIME, orderStartTime);
        }
        if (CheckUtil.objIsNotEmpty(orderEndTime)) {
            queryWrapper.le(OaCOrderPersonal.ORDER_TIME, orderEndTime);
        }
        if (CheckUtil.objIsNotEmpty(passengerName)) {
            queryWrapper.like(OaCOrderPersonal.PASSENGER_NAME, passengerName);
        }
        if (CheckUtil.objIsNotEmpty(passengerPhone)) {
            queryWrapper.like(OaCOrderPersonal.PASSENGER_PHONE, passengerPhone);
        }
        if (CheckUtil.objIsNotEmpty(driverName) || CheckUtil.objIsNotEmpty(driverPhone)) {
            List<OaDUser> driveList = getOaDuserListByDriverName(driverName, driverPhone);
            if (!driveList.isEmpty()) {
                List<Long> userIdList = new ArrayList<>();
                for (OaDUser u : driveList) {
                    userIdList.add(u.getDriverId());
                }
                queryWrapper.in(OaCOrderPersonal.DRIVER_ID, userIdList);
            } else {
                return list;
            }
        }
        if (CheckUtil.objIsNotEmpty(isRefund)) {
            queryWrapper.eq(OaCOrderPersonal.IS_REFUND, isRefund);
        }
        if (CheckUtil.objIsNotEmpty(startAddress)) {
            queryWrapper.like(OaCOrderPersonal.START_ADDRESS, startAddress);
        }
        if (CheckUtil.objIsNotEmpty(endAddress)) {
            queryWrapper.like(OaCOrderPersonal.END_ADDRESS, endAddress);
        }
        if (CheckUtil.objIsNotEmpty(vehNo)) {
            List<OaSysVehicle> vehList = getVehicleListByVehNo(vehNo);
            if (!vehList.isEmpty()) {
                List<Long> vehicleIdList = new ArrayList<>();
                for (OaSysVehicle v : vehList) {
                    vehicleIdList.add(v.getVehicleId());
                }
                queryWrapper.in(OaCOrderPersonal.VEHICLE_ID, vehicleIdList);
            } else {
                return list;
            }
        }
        if (CheckUtil.objIsNotEmpty(orderNo)) {
            queryWrapper.like(OaCOrderPersonal.ORDER_NO, orderNo);
        }
        if (CheckUtil.objIsNotEmpty(status)) {
            queryWrapper.eq(OaCOrderPersonal.ORDER_STATUS, status);
        }
        list = oacOrderPersonalMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * 获取部门列表
     *
     * @param cmsOadOrderPersonalParam
     * @return
     */
    @Override
    public Rv getCmsOrderStatusList(CmsOadOrderPersonalParam cmsOadOrderPersonalParam) {
        Long sysUserId = TokenUtil.getTokenUserId();
        List<String> dataScope = TokenUtil.getRoleDataScope();
        if (CheckUtil.objIsEmpty(dataScope) || CheckUtil.objIsEmpty(sysUserId)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        List<CmsOrderStatusListRes> resList = new ArrayList<>();
        //查询订单状态列表
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaSysDict.TAG, TokenUtil.getTag());
        queryWrapper.eq(OaSysDict.TYPE, OaCOrderPersonalOfficial.ORDER_STATUS);
        queryWrapper.eq(OaSysDict.EXPAND3, "didi");
        List<OaSysDict> list = oaSysDictMapper.selectList(queryWrapper);
        if (CheckUtil.objIsEmpty(list)) {
            return Rv.wrap(resList);
        }
        CmsOrderStatusListRes res = null;
        for (OaSysDict d : list) {
            res = new CmsOrderStatusListRes();
            res.setStatus(Integer.parseInt(d.getValue()));
            res.setStatusStr(d.getLabel());
            resList.add(res);
        }
        //返回查询结果
        return Rv.wrap(resList);
    }

    @Override
    public Rv ownexpenseTrajectory(String orderNo) {
        // ###########################################################测试专用
//        OaDVehicleGps oaDVehicleGps = new OaDVehicleGps();
//        oaDVehicleGps.setDriverId(759915507974144L);
//        oaDVehicleGps.setVehId(759925492350976L);
//        oaDVehicleGps.setLng("116.417428");
//        oaDVehicleGps.setLat("39.91923");
//        oaDVehicleGps.setVehType(0);
//        oaDVehicleGps.setIsTrue(0);
//        boolean set = redisCommon.set(RedisPrefixConstant.GPS_VEH_KEY_PREFIX + "759915507974144", JSON.toJSONString(oaDVehicleGps));
//        System.out.println(set+"=====================================================================================================");
//        // ###########################################################
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select(OaDVehicleGpsHistory.LNG, OaDVehicleGpsHistory.LAT);
        queryWrapper.eq(OaDVehicleGpsHistory.ORDER_NO, orderNo);
        List<OaDVehicleGpsHistory> list = oaDVehicleGpsHistoryMapper.selectList(queryWrapper);
        if (CheckUtil.collectionIsEmpty(list)) {
            throw PangException.create(EErrorCode.orderNoGPSInfo);
        }
        List<String> collectionLngLat = new ArrayList<>();
        for (OaDVehicleGpsHistory oaDVehicleGpsHistory : list) {
            collectionLngLat.add(oaDVehicleGpsHistory.getLng() + "," + oaDVehicleGpsHistory.getLat());
        }
        return Rv.wrap(collectionLngLat);
    }

    /**
     * @param orderId：订单ID
     * @return
     */
    @Override
    public Rv getOrderPersonalId(String orderId) {
        if (CheckUtil.objIsEmpty(orderId)) {
            throw PangException.create(EErrorCode.unLoginError);
        }
        QueryWrapper<OaCOrderPersonal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaCOrderPersonal.ORDER_NO, orderId);
        List<OaCOrderPersonal> oaCOrderPersonals = oacOrderPersonalMapper.selectList(queryWrapper);
        if (oaCOrderPersonals.size() == 0) {
            throw PangException.create(EErrorCode.unKnowParams);
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("personalId", oaCOrderPersonals.get(0).getPersonalId());
        hashMap.put("orderStatus", oaCOrderPersonals.get(0).getOrderStatus());
        return Rv.wrap(hashMap);
    }

    /**
     * 查詢司机ID
     *
     * @param orderList
     * @return
     */
    public List<String> dUsedIdDriverPhoneORDriverName(OrderList orderList) {
        List<String> dUsedId = new ArrayList<>();
        if (CheckUtil.strIsNotEmpty(orderList.getDriverName())) {
            QueryWrapper<OaDUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(OaDUser.DRIVER_NAME, orderList.getDriverName());
            if (CheckUtil.strIsNotEmpty(orderList.getDriverPhone())) {
                queryWrapper.like(OaDUser.DRIVER_PHONE, orderList.getDriverPhone());
            }
            queryWrapper.select(OaDUser.DRIVER_ID);
            List<OaDUser> oaDUserList = oadUserMapper.selectList(queryWrapper);
            if (CheckUtil.objIsNotEmpty(oaDUserList)) {
                for (int i = 0; i < oaDUserList.size(); i++) {
                    dUsedId.add(String.valueOf(oaDUserList.get(i).getDriverId()));
                }
            }

        }

        //if (CheckUtil.strIsNotEmpty(orderList.getDriverPhone())) {
        //    QueryWrapper<OaDUser> queryWrapper = new QueryWrapper<>();
        //    if (CheckUtil.strIsNotEmpty(orderList.getDriverPhone())) {
        //        queryWrapper.like(OaDUser.DRIVER_PHONE, orderList.getDriverPhone());
        //        queryWrapper.select(OaDUser.DRIVER_ID);
        //    }
        //    List<OaDUser> oaDUserList = oadUserMapper.selectList(queryWrapper);
        //    for (int i = 0; i < oaDUserList.size(); i++) {
        //        dUsedId.add(String.valueOf(oaDUserList.get(i).getDriverId()));
        //    }
        //}
        return dUsedId;
    }

    /**
     * 查询车辆ID
     *
     * @param orderList
     * @return
     */
    public List<String> vehicleIdVehNo(OrderList orderList) {
        List<String> vehicleId = new ArrayList<>();
        if (CheckUtil.strIsNotEmpty(orderList.getVehNo())) {
            QueryWrapper<OaSysVehicle> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(OaSysVehicle.VEH_NO, orderList.getVehNo());
            queryWrapper.select(OaSysVehicle.VEHICLE_ID);
            List<OaSysVehicle> oaSysVehicleList = oaSysVehicleMapper.selectList(queryWrapper);
            if (CheckUtil.objIsNotEmpty(oaSysVehicleList)) {
                for (int i = 0; i < oaSysVehicleList.size(); i++) {
                    vehicleId.add(String.valueOf(oaSysVehicleList.get(i).getVehicleId()));
                }
            }
        }
        return vehicleId;
    }


    /**
     * 重新编写订单列表的接口
     *
     * @return
     */
    @Override
    public Rv getNewOrderList(OrderList orderList) {
        long userId = TokenUtil.getTokenUserId();
        List<Long> offices = iOaSysGetOfficeIdListService.selectOfficeIdList(userId);
        if (offices.size() == 0) {
            return Rv.wrap();
        }
        Long mOfficeId = orderList.getOfficeId();
        if (mOfficeId != null) {
            if (offices.contains(mOfficeId)) {
                offices.clear();
                offices.add(mOfficeId);
            } else {
                return Rv.error(EErrorCode.authErr);
            }
        }

        List<Date> timeList = orderList.getTimeList();
        if (CheckUtil.objIsNotEmpty(timeList)) {
            if (timeList.size() == 2) {
                if (CheckUtil.objIsNotEmpty(timeList.get(0))) {
                    orderList.setOrderStartTime(timeList.get(0));
                }
                if (CheckUtil.objIsNotEmpty(timeList.get(1))) {
                    orderList.setOrderEndTime(timeList.get(1));
                }
            } else {
                throw PangException.create(EErrorCode.missingArg);
            }
        }
        List<String> dUsedIdDriverPhoneORDriverName = this.dUsedIdDriverPhoneORDriverName(orderList);
        if (
                (CheckUtil.objIsEmpty(dUsedIdDriverPhoneORDriverName) && CheckUtil.strIsNotEmpty(orderList.getDriverName())) ||
                        (CheckUtil.objIsEmpty(dUsedIdDriverPhoneORDriverName) && CheckUtil.strIsNotEmpty(orderList.getDriverPhone()))
        ) {
            return Rv.wrap(new Page());
        }

        List<String> vehicleIdVehNo = this.vehicleIdVehNo(orderList);
        if (CheckUtil.objIsEmpty(vehicleIdVehNo) && CheckUtil.strIsNotEmpty(orderList.getVehNo())) {
            return Rv.wrap(new Page());
        }

        Long preOfficeId = null;
        if (orderList.getAcceptOrder()) {
            preOfficeId = oaSysUserMapper.checkUserAuth(userId);
            offices = Collections.emptyList();
        }
        // 创建分页器
        IPage iPage = new Page();
        // 设置需要查询的页码
        iPage.setCurrent(orderList.getPage());
        // 设置每页需要显示的数据量
        iPage.setSize(orderList.getPageSize());
        // 开始进行订单查询
        List<OrderList> newOrderList = null;
        if (orderList.getOrderType().equals("7")) {
            newOrderList = oaDOrderMapper.getCharterOrderList(
                    iPage, // 分页器
                    orderList.getOrderNo(),// 订单编号
                    orderList.getOrderStatus(), // 订单状态
                    orderList.getPassengerName(), //乘客姓名
                    orderList.getPassengerPhone(), // 乘客手机号
                    orderList.getCityId(), // 城市Code
                    orderList.getIsChangePrice(), // 是否改价
                    orderList.getStartAddress(), // 出发地地址
                    orderList.getEndAddress(), // 目的地地址
                    orderList.getIsRefund(), // 是否退款
                    orderList.getBusinessType(), // 业务类型
                    orderList.getCancelReason(), // 取消原因
                    orderList.getOrderStartTime(), // 预约开始时间
                    orderList.getOrderEndTime(), // 预约到达时间
                    orderList.getOrderType(), // 订单类型
                    orderList.getDidiOrderId(), // 流量方订单ID
                    orderList.getOrderChannel(), // 订单渠道(0-普通 1-滴滴)
                    dUsedIdDriverPhoneORDriverName, // 司机ID(0-普通 1-滴滴)
                    vehicleIdVehNo, // 车辆ID(0-普通 1-滴滴)
                    offices,//可查看部门
                    orderList.getPersonalId(),
                    preOfficeId
            );
        } else {
            newOrderList = oaDOrderMapper.getNewOrderList(
                    iPage, // 分页器
                    orderList.getOrderNo(),// 订单编号
                    orderList.getOrderStatus(), // 订单状态
                    orderList.getPassengerName(), //乘客姓名
                    orderList.getPassengerPhone(), // 乘客手机号
                    orderList.getCityId(), // 城市Code
                    orderList.getIsChangePrice(), // 是否改价
                    orderList.getStartAddress(), // 出发地地址
                    orderList.getEndAddress(), // 目的地地址
                    orderList.getIsRefund(), // 是否退款
                    orderList.getBusinessType(), // 业务类型
                    orderList.getCancelReason(), // 取消原因
                    orderList.getOrderStartTime(), // 预约开始时间
                    orderList.getOrderEndTime(), // 预约到达时间
                    orderList.getOrderType(), // 订单类型
                    orderList.getDidiOrderId(), // 流量方订单ID
                    orderList.getOrderChannel(), // 订单渠道(0-普通 1-滴滴)
                    dUsedIdDriverPhoneORDriverName, // 司机ID(0-普通 1-滴滴)
                    vehicleIdVehNo, // 车辆ID(0-普通 1-滴滴)
                    offices,//可查看部门
                    orderList.getPersonalId(),
                    preOfficeId
            );
        }
        if (orderList.getAcceptOrder()) {
            List<OrderList> tmpList = null;
            //包车类型
            if (orderList.getOrderType().equals("7")) {
                tmpList = oaDOrderMapper.getCharterOrderList(
                        iPage, // 分页器
                        orderList.getOrderNo(),// 订单编号
                        EOrderStatus.driverOrder.getType().toString(), // 订单状态
                        orderList.getPassengerName(), //乘客姓名
                        orderList.getPassengerPhone(), // 乘客手机号
                        orderList.getCityId(), // 城市Code
                        orderList.getIsChangePrice(), // 是否改价
                        orderList.getStartAddress(), // 出发地地址
                        orderList.getEndAddress(), // 目的地地址
                        orderList.getIsRefund(), // 是否退款
                        orderList.getBusinessType(), // 业务类型
                        orderList.getCancelReason(), // 取消原因
                        orderList.getOrderStartTime(), // 预约开始时间
                        orderList.getOrderEndTime(), // 预约到达时间
                        orderList.getOrderType(), // 订单类型
                        orderList.getDidiOrderId(), // 流量方订单ID
                        orderList.getOrderChannel(), // 订单渠道(0-普通 1-滴滴)
                        dUsedIdDriverPhoneORDriverName, // 司机ID(0-普通 1-滴滴)
                        vehicleIdVehNo, // 车辆ID(0-普通 1-滴滴)
                        offices,//可查看部门
                        orderList.getPersonalId(),
                        preOfficeId
                );
            } else {
                tmpList = oaDOrderMapper.getNewOrderList(
                        iPage, // 分页器
                        orderList.getOrderNo(),// 订单编号
                        EOrderStatus.driverOrder.getType().toString(), // 订单状态
                        orderList.getPassengerName(), //乘客姓名
                        orderList.getPassengerPhone(), // 乘客手机号
                        orderList.getCityId(), // 城市Code
                        orderList.getIsChangePrice(), // 是否改价
                        orderList.getStartAddress(), // 出发地地址
                        orderList.getEndAddress(), // 目的地地址
                        orderList.getIsRefund(), // 是否退款
                        orderList.getBusinessType(), // 业务类型
                        orderList.getCancelReason(), // 取消原因
                        orderList.getOrderStartTime(), // 预约开始时间
                        orderList.getOrderEndTime(), // 预约到达时间
                        orderList.getOrderType(), // 订单类型
                        orderList.getDidiOrderId(), // 流量方订单ID
                        orderList.getOrderChannel(), // 订单渠道(0-普通 1-滴滴)
                        dUsedIdDriverPhoneORDriverName, // 司机ID(0-普通 1-滴滴)
                        vehicleIdVehNo, // 车辆ID(0-普通 1-滴滴)
                        offices,//可查看部门
                        orderList.getPersonalId(),
                        preOfficeId
                );
            }
            newOrderList.addAll(tmpList);
        }

        // 如果订单集合中为0则终止运行
        if (CheckUtil.objIsEmpty(newOrderList)) {
            return Rv.wrap(iPage);
        }
        // 创建系统字典表in查询的List
        List<String> dictValues = new ArrayList<>();
        dictValues.add("order_type");
        dictValues.add("order_status");
        dictValues.add("require_level");
        dictValues.add("cancel_reason");
        dictValues.add("order_channel");
        // 开始进行系统字典表查询
        List<OaSysDict> dictList = this.getDictList(OaSysDict.TYPE, dictValues);
        // 创建城市字典表in查询的List
        List<String> areaList = new ArrayList<>();
        // 司机表in查询List
        List<String> dUserList = new ArrayList<>();
        // 车辆信息系表in查询List
        List<String> vehicleList = new ArrayList<>();
        // 开始进行系统字典的数据拼接装载城市code
        for (int i = 0; i < newOrderList.size(); i++) {
            areaList.add(newOrderList.get(i).getCityId());
            if (CheckUtil.strIsNotEmpty(newOrderList.get(i).getDriverId())) {
                dUserList.add(newOrderList.get(i).getDriverId());
            }
            if (CheckUtil.strIsNotEmpty(newOrderList.get(i).getVehicleId())) {
                vehicleList.add(newOrderList.get(i).getVehicleId());
            }
            for (int j = 0; j < dictList.size(); j++) {
                if (null != newOrderList.get(i).getOrderType() && dictList.get(j).getType().equals("order_type") && newOrderList.get(i).getOrderType().equals(dictList.get(j).getValue())) {
                    newOrderList.get(i).setOrderTypeStr(dictList.get(j).getLabel());
                }
                if (CheckUtil.strIsNotEmpty(newOrderList.get(i).getOrderStatus()) && dictList.get(j).getType().equals("order_status") && newOrderList.get(i).getOrderStatus().equals(dictList.get(j).getValue())) {
                    newOrderList.get(i).setOrderStatusStr(dictList.get(j).getLabel());
                }
                if (CheckUtil.strIsNotEmpty(newOrderList.get(i).getVehicleType()) && dictList.get(j).getType().equals("require_level") && newOrderList.get(i).getVehicleType().equals(dictList.get(j).getValue())) {
                    newOrderList.get(i).setVehicleTypeStr(dictList.get(j).getLabel());
                }
                if (CheckUtil.strIsNotEmpty(newOrderList.get(i).getCancelReason()) && dictList.get(j).getType().equals("cancel_reason") && newOrderList.get(i).getCancelReason().equals(dictList.get(j).getValue())) {
                    newOrderList.get(i).setCancelReasonStr(dictList.get(j).getLabel());
                }
                if (CheckUtil.strIsNotEmpty(newOrderList.get(i).getOrderChannel()) && dictList.get(j).getType().equals("order_channel") && newOrderList.get(i).getOrderChannel().equals(dictList.get(j).getValue())) {
                    newOrderList.get(i).setOrderChannelStr(dictList.get(j).getLabel());
                }
            }
        }
        // 拼接城市信息
        if (CheckUtil.objIsNotEmpty(areaList)) {
            // 开始进行城市字典表查询
            List<OaSysArea> dictArea = this.getDictArea(OaSysArea.AD_CODE, areaList);
            // 开始进行城市字典的数据拼接
            for (int i = 0; i < newOrderList.size(); i++) {
                for (int j = 0; j < dictArea.size(); j++) {
                    if (null != newOrderList.get(i).getCityId() && newOrderList.get(i).getCityId().equals(dictArea.get(j).getAdCode())) {
                        newOrderList.get(i).setCityStr(dictArea.get(j).getName());
                    }
                }
            }
        }
        // 拼接司机信息
        if (!orderList.getOrderType().equals("7")) {
            if (CheckUtil.objIsNotEmpty(dUserList)) {
                QueryWrapper<OaDUser> queryWrapper = new QueryWrapper<>();
                queryWrapper.in(OaDUser.DRIVER_ID, dUserList);
                List<OaDUser> oaDUserList = oadUserMapper.selectList(queryWrapper);
                for (int i = 0; i < newOrderList.size(); i++) {
                    for (int j = 0; j < oaDUserList.size(); j++) {
                        if (null != newOrderList.get(i).getDriverId() && newOrderList.get(i).getDriverId().equals(String.valueOf(oaDUserList.get(j).getDriverId()))) {
                            newOrderList.get(i).setDriverName(oaDUserList.get(j).getDriverName());
                            newOrderList.get(i).setDriverPhone(oaDUserList.get(j).getDriverPhone());
                        }
                    }
                }
            }
        } else {
            //用c_order_personal中的rule_no去charter_detail查询运力匹配
            for (int i = 0; i < newOrderList.size(); i++) {
                if (CheckUtil.objIsNotEmpty(newOrderList.get(i).getOrderNo())) {
                    List<Long> driverIds = new ArrayList<>();
                    QueryWrapper<OaDOrderCharteredDetail> charterDetailQuery = new QueryWrapper<>();
                    charterDetailQuery.eq(OaDOrderCharteredDetail.ORDER_NO, newOrderList.get(i).getOrderNo());
                    List<OaDOrderCharteredDetail> charteredDetails = oaDOrderCharteredDetailMapper.selectList(charterDetailQuery);
                    if (CheckUtil.objIsEmpty(charteredDetails)) {
                        continue;
                    }
                    for (OaDOrderCharteredDetail oaDOrderCharterDetail : charteredDetails
                    ) {
                        if (CheckUtil.objIsNotEmpty(oaDOrderCharterDetail.getDriverId())) {
                            newOrderList.get(i).setHasDriver(true);
                            driverIds.add(oaDOrderCharterDetail.getDriverId());
                        }
                    }
                    newOrderList.get(i).setOrderCharteredDetails(charteredDetails);
                    newOrderList.get(i).setDriverIds(driverIds);
                }
            }
        }
        // 拼接车辆信息
        if (CheckUtil.objIsNotEmpty(vehicleList)) {
            QueryWrapper<OaSysVehicle> queryWrapper = new QueryWrapper<>();
            queryWrapper.in(OaSysVehicle.VEHICLE_ID, vehicleList);
            List<OaSysVehicle> oaSysVehicleList = oaSysVehicleMapper.selectList(queryWrapper);
            for (int i = 0; i < newOrderList.size(); i++) {
                for (int j = 0; j < oaSysVehicleList.size(); j++) {
                    if (null != newOrderList.get(i).getVehicleId() && newOrderList.get(i).getVehicleId().equals(String.valueOf(oaSysVehicleList.get(j).getVehicleId()))) {
                        newOrderList.get(i).setVehNo(oaSysVehicleList.get(j).getVehNo());
                    }
                }
            }
        }
        // 向records装载拼接的数据信息
        iPage.setRecords(newOrderList);
        // 返回
        return Rv.wrap(iPage);
    }

    /**
     * 取消携程订单
     *
     * @param orderNo
     * @return
     */
    @Override
    public Rv cancelXCOrder(String orderNo) {
        TokenUser tokenUser = TokenUtil.getTokenUser();
        if (CheckUtil.objIsEmpty(tokenUser)) {
            throw PangException.create(EErrorCode.notFoundYourName);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timeStamp = sdf.format(System.currentTimeMillis());
        //根据orderNo查询order_personal表
        XieChengResponse response = new XieChengResponse();
        OaCOrderPersonal oaCOrderPersonal = new OaCOrderPersonal();
        try {
            QueryWrapper<OaCOrderPersonal> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(OaCOrderPersonal.ORDER_NO, orderNo);
            oaCOrderPersonal = oacOrderPersonalMapper.selectOne(queryWrapper);
            String action = "order/cancel";
            CancelOrderRequest requestParam = new CancelOrderRequest();
            requestParam.setVendorOrderID(oaCOrderPersonal.getPersonalId().toString());
            requestParam.setCtripPurchaseOrderID(Long.parseLong(orderNo));
            String params = XieChengUtil.encodeDES(secretKey, JSON.toJSONString(requestParam)).toUpperCase();
            String sign = XieChengUtil.getCallbackSign(venderId, timeStamp, params.length(), secretKey);
            String url = callback + "/" + channel + "-" + venderId + "/" + action + "/" + version + "/" + orderNo + "/" + timeStamp + "/" + sign;
            String result = HttpRequestUtil.requestPostJson(url, params);
            response = JSON.parseObject(result, XieChengResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (response != null) {
            if (EXieChengResponseConstant.OK.getCode().equalsIgnoreCase(response.getMsgCode())) {
                //成功之后更新表数据
                oaCOrderPersonal.setOrderStatus(EOrderStatus.officeCancelOrder.getType());
                oacOrderPersonalMapper.updateById(oaCOrderPersonal);
                operateLog(oaCOrderPersonal, tokenUser, "将订单：" + oaCOrderPersonal.getOrderNo() + "付费改派了", null);
                return Rv.wrap();
            }
            log.info("取消携程订单失败：" + response.getMessage());
        }
        return Rv.error(EErrorCode.applyAmountOperateFailure);
    }

    @Override
    public Rv updateXCLastPushDriverTime() {
        QueryWrapper<OaCOrderPersonal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaCOrderPersonal.ORDER_CHANNEL, 3);//携程
        queryWrapper.eq(OaCOrderPersonal.ORDER_STATUS, 0);//等待应答
        queryWrapper.isNull(OaCOrderPersonal.LAST_PUSH_DRIVER_TIME);
        List<OaCOrderPersonal> oaCOrderPersonalList = oacOrderPersonalMapper.selectList(queryWrapper);
        if (oaCOrderPersonalList.size() <= 0) {
            return Rv.error(EErrorCode.updateIsNull);
        }
        for (OaCOrderPersonal info : oaCOrderPersonalList) {
            if (CheckUtil.objIsNotEmpty(info.getLastPushDriverTime())) {
                continue;
            }
            //查询携程订单的当前详细信息，用来保证异常状态下供应商与携程的订单状态与信息一致
            OrderDetailRequest orderDetailRequest = new OrderDetailRequest();
            orderDetailRequest.setCtripPurchaseOrderID(Long.parseLong(info.getOrderNo()));
            orderDetailRequest.setVendorOrderID(info.getPersonalId().toString());
            try {
                String res = sendToXC(info.getOrderNo(), JSON.toJSONString(orderDetailRequest));
                log.info("XC查询订单详情res：{}", JSON.toJSONString(res));
                OrderDetailResponse orderDetailResponse = JSON.parseObject(res, OrderDetailResponse.class);
                if (CheckUtil.objIsNotEmpty(orderDetailResponse.getOrderDetailRuleDO())) {
                    //最晚确认司机时间
                    String lastPushDriverTime = orderDetailResponse.getOrderDetailRuleDO().getLastPushDriverTime();
                    info.setLastPushDriverTime(lastPushDriverTime);
                    oacOrderPersonalMapper.updateById(info);
                }
            } catch (Exception e) {
                log.info("XC查询订单详情异常-->" + e.getMessage());
            }
        }
        return Rv.wrap();
    }

    /**
     * 请求携程查询订单详情
     *
     * @param orderId
     * @param body
     * @return
     */
    private static String sendToXC(String orderId, String body) {
        //供应商ID
        String venderId = "1000427";
        //渠道
        String channel = "JNT";
        //版本
        String version = "2.0";
        //携程密钥
        String secretKey = "1k(Ri^n1";
        //URL
        //String callback = "http://openapi.car.ctrip.com/chvendormessagebus";
        //接口名
        String action = "order/detail";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timeStamp = sdf.format(System.currentTimeMillis());
        log.info("XCBody-" + body);
        String params = "";
        try {
            params = XieChengUtil.encodeDES(secretKey, body);
            params = params.toUpperCase();
            log.info("XCParams-" + params);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        String sign = XieChengUtil.getCallbackSign(venderId, timeStamp, params.length(), secretKey);
        log.info("XCSign-" + sign);

        String url = callbackUrl + "/" + channel + "-" + venderId + "/" + action + "/" + version + "/" + orderId + "/" + timeStamp + "/" + sign;
        String result = null;
        try {
            log.info("XCUrl-" + url);
            result = HttpRequestUtil.requestPostJson(url, params);
            log.info("XCResult-" + result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    //开发者使用
    public static void main(String[] args) {
        //查询携程订单的当前详细信息，用来保证异常状态下供应商与携程的订单状态与信息一致
        OrderDetailRequest orderDetailRequest = new OrderDetailRequest();
        orderDetailRequest.setCtripPurchaseOrderID(881825152060011886L);
        orderDetailRequest.setVendorOrderID("2203291016003584");
        String res = sendToXC("881825152060011886", JSON.toJSONString(orderDetailRequest));
        OrderDetailResponse orderDetailResponse = JSON.parseObject(res, OrderDetailResponse.class);
        //最晚确认司机时间
        String lastPushDriverTime = orderDetailResponse.getOrderDetailRuleDO().getLastPushDriverTime();
    }

    /**
     * 导出订单信息
     *
     * @param orderList
     * @return
     */
    @Override
    public Rv getNewExportOrderExcel(OrderList orderList) {
        long userId = TokenUtil.getTokenUserId();
        Long officeId = orderList.getOfficeId();
        List<Long> offices = iOaSysGetOfficeIdListService.selectOfficeIdList(userId);
        if (officeId != null) {
            if (offices.contains(officeId)) {
                offices = new ArrayList<>();
                offices.add(officeId);
            } else {
                return Rv.error(EErrorCode.authErr);
            }
        }

        try {
            LinkedHashSet<Long> hashSet = new LinkedHashSet<>(offices);
            offices = new ArrayList<>(hashSet);
            List<Date> timeList = orderList.getTimeList();
            if (CheckUtil.objIsNotEmpty(timeList)) {
                if (timeList.size() == 2) {
                    if (CheckUtil.objIsNotEmpty(timeList.get(1))) {
                        orderList.setOrderEndTime(timeList.get(1));
                    }
                    if (CheckUtil.objIsNotEmpty(timeList.get(0))) {
                        orderList.setOrderStartTime(timeList.get(0));
                    }
                } else {
                    throw PangException.create(EErrorCode.missingArg);
                }
            }
            List<String> dUsedIdDriverPhoneORDriverName = this.dUsedIdDriverPhoneORDriverName(orderList);
            if (CheckUtil.objIsNotEmpty(dUsedIdDriverPhoneORDriverName)) {
                orderList.setDirverIds(dUsedIdDriverPhoneORDriverName);
            }
            List<String> vehicleIdVehNo = this.vehicleIdVehNo(orderList);
            if (CheckUtil.objIsNotEmpty(vehicleIdVehNo)) {
                orderList.setVehicleIds(vehicleIdVehNo);
            }
            List<OrderList> resultOrderLists = oaSysOrderDetailsMapper.allOrderInfo(orderList, offices);
            List<OrderList> reList = new ArrayList<>();
            if (CheckUtil.strIsEmpty(orderList.getOrderType()) || !orderList.getOrderType().equals("7")) {
                for (OrderList order : resultOrderLists) {
                    if (!order.getOrderType().equals("7")) {
                        reList.add(order);
                    }
                }
            }
            if ("7".equals(orderList.getOrderType())) {
                for (OrderList order : resultOrderLists) {
                    if (order.getOrderType().equals("7")) {
                        reList.add(order);
                    }
                }
            }
            return Rv.wrap(reList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 多线程进行并发查询订单数据
     *
     * @param orderList
     */
    private List<OrderList> threadPoolDeal(OrderList orderList, List<Long> offices) {
        boolean result = false;
        List<OrderList> resultOrderList = new ArrayList<>();
        List<String> threadTaskList = new ArrayList<>();
        threadTaskList.add("one");
        threadTaskList.add("two");
        threadTaskList.add("three");
        threadTaskList.add("four");
        threadTaskList.add("five");
        threadTaskList.add("six");
        threadTaskList.add("seven");
        // 声明execl结果集

        // 线程池任务处理结果集
        List<Future<HashMap<String, Object>>> futureList = new ArrayList<>();
        // 如下内容多线程处理方法
        try {
            for (int i = 0; i < threadTaskList.size(); i++) {
                String dealQueue = threadTaskList.get(i);
                //提交任务到线程池
                Future<HashMap<String, Object>> future = executor.submit(new Callable<HashMap<String, Object>>() {
                    @Override
                    public HashMap<String, Object> call() {
                        // 任务处理
                        HashMap<String, Object> hashMapResults = executorDeal(dealQueue, orderList, offices);


                        // 设置返回结果，用于计算是否所有线程已处理完
                        return new HashMap<String, Object>(16) {
                            {
                                this.put("futureKey", "1");
                                this.put("hashMapResults", hashMapResults);
                            }
                        };
                    }
                });
                futureList.add(future);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 此时需要获取上面异步任务的执行结果
        boolean flag = true;
        while (flag) {
            if (!futureList.isEmpty()) {
                int count = 0;
                List<HashMap<String, Object>> hashMapResultsList = new ArrayList<>();
                for (Future future : futureList) {
                    //异步任务完成并且未被取消，则获取返回的结果
                    if (future.isDone() && !future.isCancelled()) {
                        try {
                            HashMap<String, Object> futureResult = (HashMap<String, Object>) future.get();
                            if (CheckUtil.objIsNotEmpty(futureResult.get("futureKey")) && futureResult.get("futureKey") != "") {
                                count = count + Integer.valueOf(futureResult.get("futureKey").toString());
                                HashMap<String, Object> hashMapResults = (HashMap<String, Object>) futureResult.get("hashMapResults");
                                hashMapResultsList.add(hashMapResults);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                }
                // 判断是否所有任务已处理完成
                if (count == threadTaskList.size()) {
                    result = true;
                    flag = false;

                    if (CheckUtil.collectionIsNotEmpty(hashMapResultsList)) {
                        for (int i = 0; i < hashMapResultsList.size(); i++) {
                            if (Objects.equals(hashMapResultsList.get(i).get("dealQueue"), "one")) {
                                List<OrderList> orderLists = (List<OrderList>) hashMapResultsList.get(i).get("results");
                                if (resultOrderList.size() == 0) {
                                    for (int j = 0; j < orderLists.size(); j++) {
                                        OrderList orderListItem = new OrderList();
                                        orderListItem.setOrderNo(orderLists.get(j).getOrderNo());
                                        orderListItem.setCityStr(orderLists.get(j).getCityStr() != null ? orderLists.get(j).getCityStr() : "");
                                        orderListItem.setVehicleTypeStr(orderLists.get(j).getVehicleTypeStr() != null ? String.valueOf(orderLists.get(j).getVehicleTypeStr()) : "");
                                        orderListItem.setVehNo(orderLists.get(j).getVehNo() != null ? String.valueOf(orderLists.get(j).getVehNo()) : "");
                                        orderListItem.setOrderChannelStr(orderLists.get(j).getOrderChannelStr() != null ? orderLists.get(j).getOrderChannelStr() : "");
                                        orderListItem.setOrderTypeStr(orderLists.get(j).getOrderTypeStr() != null ? orderLists.get(j).getOrderTypeStr() : "");
                                        resultOrderList.add(orderListItem);
                                    }
                                } else if (resultOrderList.size() == orderLists.size()) {
                                    for (int j = 0; j < orderLists.size(); j++) {
                                        resultOrderList.get(j).setOrderNo(orderLists.get(j).getOrderNo());
                                        resultOrderList.get(j).setCityStr(orderLists.get(j).getCityStr() != null ? orderLists.get(j).getCityStr() : "");
                                        resultOrderList.get(j).setVehicleTypeStr(orderLists.get(j).getVehicleTypeStr() != null ? String.valueOf(orderLists.get(j).getVehicleTypeStr()) : "");
                                        resultOrderList.get(j).setVehNo(orderLists.get(j).getVehNo() != null ? String.valueOf(orderLists.get(j).getVehNo()) : "");
                                    }
                                }
                            } else if (Objects.equals(hashMapResultsList.get(i).get("dealQueue"), "two")) {
                                List<OrderList> orderLists = (List<OrderList>) hashMapResultsList.get(i).get("results");
                                if (resultOrderList.size() == 0) {
                                    for (int j = 0; j < orderLists.size(); j++) {
                                        OrderList orderListItem = new OrderList();
                                        orderListItem.setDriverName(orderLists.get(j).getDriverName() != null ? String.valueOf(orderLists.get(j).getDriverName()) : "");
                                        orderListItem.setDriverPhone(orderLists.get(j).getDriverPhone() != null ? String.valueOf(orderLists.get(j).getDriverPhone()) : "");
                                        orderListItem.setOrderStatusStr(orderLists.get(j).getOrderStatusStr() != null ? String.valueOf(orderLists.get(j).getOrderStatusStr()) : "");
                                        orderListItem.setUserPhone(orderLists.get(j).getUserPhone() != null ? String.valueOf(orderLists.get(j).getUserPhone()) : "");
                                        orderListItem.setCancelReasonStr(orderLists.get(j).getCancelReasonStr() != null ? String.valueOf(orderLists.get(j).getCancelReasonStr()) : "");
                                        orderListItem.setVehicleTeam(orderLists.get(j).getVehicleTeam() != null ? String.valueOf(orderLists.get(j).getVehicleTeam()) : "");
                                        resultOrderList.add(orderListItem);
                                    }
                                } else if (resultOrderList.size() == orderLists.size()) {
                                    for (int j = 0; j < orderLists.size(); j++) {
                                        resultOrderList.get(j).setDriverName(orderLists.get(j).getDriverName() != null ? String.valueOf(orderLists.get(j).getDriverName()) : "");
                                        resultOrderList.get(j).setDriverPhone(orderLists.get(j).getDriverPhone() != null ? String.valueOf(orderLists.get(j).getDriverPhone()) : "");
                                        resultOrderList.get(j).setOrderStatusStr(orderLists.get(j).getOrderStatusStr() != null ? String.valueOf(orderLists.get(j).getOrderStatusStr()) : "");
                                        resultOrderList.get(j).setUserPhone(orderLists.get(j).getUserPhone() != null ? String.valueOf(orderLists.get(j).getUserPhone()) : "");
                                        resultOrderList.get(j).setCancelReasonStr(orderLists.get(j).getCancelReasonStr() != null ? String.valueOf(orderLists.get(j).getCancelReasonStr()) : "");
                                        resultOrderList.get(j).setVehicleTeam(orderLists.get(j).getVehicleTeam() != null ? String.valueOf(orderLists.get(j).getVehicleTeam()) : "");
                                    }
                                }
                            } else if (Objects.equals(hashMapResultsList.get(i).get("dealQueue"), "three")) {
                                List<OrderList> orderLists = (List<OrderList>) hashMapResultsList.get(i).get("results");
                                if (resultOrderList.size() == 0) {
                                    for (int j = 0; j < orderLists.size(); j++) {
                                        OrderList orderListItem = new OrderList();
                                        orderListItem.setStartAddress(orderLists.get(j).getStartAddress() != null ? orderLists.get(j).getStartAddress() : "");
                                        orderListItem.setEndAddress(orderLists.get(j).getEndAddress() != null ? orderLists.get(j).getEndAddress() : "");
                                        orderListItem.setActualFee(orderLists.get(j).getActualFee() != null ? String.valueOf(orderLists.get(j).getActualFee()) : "");
                                        resultOrderList.add(orderListItem);
                                    }
                                } else if (resultOrderList.size() == orderLists.size()) {
                                    for (int j = 0; j < orderLists.size(); j++) {
                                        resultOrderList.get(j).setStartAddress(orderLists.get(j).getStartAddress() != null ? orderLists.get(j).getStartAddress() : "");
                                        resultOrderList.get(j).setEndAddress(orderLists.get(j).getEndAddress() != null ? orderLists.get(j).getEndAddress() : "");
                                        resultOrderList.get(j).setActualFee(orderLists.get(j).getActualFee() != null ? String.valueOf(orderLists.get(j).getActualFee()) : "");
                                    }
                                }
                            } else if (Objects.equals(hashMapResultsList.get(i).get("dealQueue"), "four")) {
                                List<OrderList> orderLists = (List<OrderList>) hashMapResultsList.get(i).get("results");
                                if (resultOrderList.size() == 0) {
                                    for (int j = 0; j < orderLists.size(); j++) {
                                        OrderList orderListItem = new OrderList();
                                        orderListItem.setDistanceFee(orderLists.get(j).getDistanceFee() != null ? orderLists.get(j).getDistanceFee() : BigDecimal.valueOf(0));
                                        orderListItem.setStartFee(orderLists.get(j).getStartFee() != null ? orderLists.get(j).getDurationFee() : BigDecimal.valueOf(0));
                                        orderListItem.setDurationFee(orderLists.get(j).getDurationFee() != null ? orderLists.get(j).getDurationFee() : BigDecimal.valueOf(0));
                                        orderListItem.setMileageFee(orderLists.get(j).getMileageFee() != null ? orderLists.get(j).getMileageFee() : BigDecimal.valueOf(0));
                                        orderListItem.setTravelCost(orderLists.get(j).getTravelCost() != null ? orderLists.get(j).getTravelCost() : BigDecimal.valueOf(0));
                                        resultOrderList.add(orderListItem);
                                    }
                                } else if (resultOrderList.size() == orderLists.size()) {
                                    for (int j = 0; j < orderLists.size(); j++) {
                                        resultOrderList.get(j).setDistanceFee(orderLists.get(j).getDistanceFee() != null ? orderLists.get(j).getDistanceFee() : BigDecimal.valueOf(0));
                                        resultOrderList.get(j).setStartFee(orderLists.get(j).getStartFee() != null ? orderLists.get(j).getDurationFee() : BigDecimal.valueOf(0));
                                        resultOrderList.get(j).setDurationFee(orderLists.get(j).getDurationFee() != null ? orderLists.get(j).getDurationFee() : BigDecimal.valueOf(0));
                                        resultOrderList.get(j).setMileageFee(orderLists.get(j).getMileageFee() != null ? orderLists.get(j).getMileageFee() : BigDecimal.valueOf(0));
                                        resultOrderList.get(j).setTravelCost(orderLists.get(j).getTravelCost() != null ? orderLists.get(j).getTravelCost() : BigDecimal.valueOf(0));
                                    }
                                }
                            } else if (Objects.equals(hashMapResultsList.get(i).get("dealQueue"), "five")) {
                                List<OrderList> orderLists = (List<OrderList>) hashMapResultsList.get(i).get("results");
                                if (resultOrderList.size() == 0) {
                                    for (int j = 0; j < orderLists.size(); j++) {
                                        OrderList orderListItem = new OrderList();
                                        orderListItem.setDidiOrderId(orderLists.get(j).getDidiOrderId() != null ? orderLists.get(j).getDidiOrderId() : "");
                                        orderListItem.setTotalFee(orderLists.get(j).getTotalFee() != null ? String.valueOf(orderLists.get(j).getTotalFee()) : "");
                                        orderListItem.setCreateTime(orderLists.get(j).getCreateTime() != null ? String.valueOf(orderLists.get(j).getCreateTime()) : "");
                                        orderListItem.setArriveTime(orderLists.get(j).getArriveTime() != null ? String.valueOf(orderLists.get(j).getArriveTime()) : "");
                                        orderListItem.setNotarizeTime(orderLists.get(j).getNotarizeTime() != null ? String.valueOf(orderLists.get(j).getNotarizeTime()) : "");
                                        orderListItem.setInitiateCollectionTime(orderLists.get(j).getInitiateCollectionTime() != null ? String.valueOf(orderLists.get(j).getInitiateCollectionTime()) : "");
                                        resultOrderList.add(orderListItem);
                                    }
                                } else if (resultOrderList.size() == orderLists.size()) {
                                    for (int j = 0; j < orderLists.size(); j++) {
                                        resultOrderList.get(j).setDidiOrderId(orderLists.get(j).getDidiOrderId() != null ? orderLists.get(j).getDidiOrderId() : "");
                                        resultOrderList.get(j).setTotalFee(orderLists.get(j).getTotalFee() != null ? String.valueOf(orderLists.get(j).getTotalFee()) : "");
                                        resultOrderList.get(j).setCreateTime(orderLists.get(j).getCreateTime() != null ? String.valueOf(orderLists.get(j).getCreateTime()) : "");
                                        resultOrderList.get(j).setArriveTime(orderLists.get(j).getArriveTime() != null ? String.valueOf(orderLists.get(j).getArriveTime()) : "");
                                        resultOrderList.get(j).setNotarizeTime(orderLists.get(j).getNotarizeTime() != null ? String.valueOf(orderLists.get(j).getNotarizeTime()) : "");
                                        resultOrderList.get(j).setInitiateCollectionTime(orderLists.get(j).getInitiateCollectionTime() != null ? String.valueOf(orderLists.get(j).getInitiateCollectionTime()) : "");
                                    }
                                }
                            } else if (Objects.equals(hashMapResultsList.get(i).get("dealQueue"), "six")) {
                                List<OrderList> orderLists = (List<OrderList>) hashMapResultsList.get(i).get("results");
                                if (resultOrderList.size() == 0) {
                                    for (int j = 0; j < orderLists.size(); j++) {
                                        OrderList orderListItem = new OrderList();
                                        orderListItem.setArriveMeetPassengerTime(orderLists.get(j).getArriveMeetPassengerTime() != null ? String.valueOf(orderLists.get(j).getArriveMeetPassengerTime()) : "");
                                        orderListItem.setPassengerPayTime(orderLists.get(j).getPassengerPayTime() != null ? String.valueOf(orderLists.get(j).getPassengerPayTime()) : "");
                                        orderListItem.setCancelOrderTime(orderLists.get(j).getCancelOrderTime() != null ? String.valueOf(orderLists.get(j).getCancelOrderTime()) : "");
                                        orderListItem.setAdditionalCost(orderLists.get(j).getAdditionalCost() != null ? orderLists.get(j).getAdditionalCost() : BigDecimal.valueOf(0));
                                        orderListItem.setOfficeName(orderLists.get(j).getOfficeName() != null ? String.valueOf(orderLists.get(j).getOfficeName()) : "");
                                        orderListItem.setAppointmentTime(orderLists.get(j).getAppointmentTime() != null ? String.valueOf(orderLists.get(j).getAppointmentTime()) : "");
                                        orderListItem.setMilageDistance(orderLists.get(j).getMilageDistance() != null ? String.valueOf(orderLists.get(j).getMilageDistance()) : "");
                                        resultOrderList.add(orderListItem);
                                    }
                                } else if (resultOrderList.size() == orderLists.size()) {
                                    for (int j = 0; j < orderLists.size(); j++) {
                                        resultOrderList.get(j).setArriveMeetPassengerTime(orderLists.get(j).getArriveMeetPassengerTime() != null ? String.valueOf(orderLists.get(j).getArriveMeetPassengerTime()) : "");
                                        resultOrderList.get(j).setPassengerPayTime(orderLists.get(j).getPassengerPayTime() != null ? String.valueOf(orderLists.get(j).getPassengerPayTime()) : "");
                                        resultOrderList.get(j).setCancelOrderTime(orderLists.get(j).getCancelOrderTime() != null ? String.valueOf(orderLists.get(j).getCancelOrderTime()) : "");
                                        resultOrderList.get(j).setAdditionalCost(orderLists.get(j).getAdditionalCost() != null ? orderLists.get(j).getAdditionalCost() : BigDecimal.valueOf(0));
                                        resultOrderList.get(j).setOfficeName(orderLists.get(j).getOfficeName() != null ? orderLists.get(j).getOfficeName() : "");
                                        resultOrderList.get(j).setAppointmentTime(orderLists.get(j).getAppointmentTime() != null ? String.valueOf(orderLists.get(j).getAppointmentTime()) : "");
                                        resultOrderList.get(j).setMilageDistance(orderLists.get(j).getMilageDistance() != null ? String.valueOf(orderLists.get(j).getMilageDistance()) : "");
                                    }
                                }
                            } else if (Objects.equals(hashMapResultsList.get(i).get("dealQueue"), "seven")) {
                                List<OrderList> orderLists = (List<OrderList>) hashMapResultsList.get(i).get("results");
                                if (resultOrderList.size() == 0) {
                                    for (int j = 0; j < orderLists.size(); j++) {
                                        OrderList orderListItem = new OrderList();
                                        orderListItem.setMeetCTime(orderLists.get(j).getMeetCTime() != null ? String.valueOf(orderLists.get(j).getMeetCTime()) : "");
                                        orderListItem.setDriverInPlaceTime(orderLists.get(j).getDriverInPlaceTime() != null ? String.valueOf(orderLists.get(j).getDriverInPlaceTime()) : "");
                                        orderListItem.setEndJourneyTime(orderLists.get(j).getEndJourneyTime() != null ? String.valueOf(orderLists.get(j).getEndJourneyTime()) : "");
                                        orderListItem.setStartJourneyTime(orderLists.get(j).getStartJourneyTime() != null ? String.valueOf(orderLists.get(j).getStartJourneyTime()) : "");
                                        resultOrderList.add(orderListItem);
                                    }
                                } else if (resultOrderList.size() == orderLists.size()) {
                                    for (int j = 0; j < orderLists.size(); j++) {
                                        resultOrderList.get(j).setMeetCTime(orderLists.get(j).getMeetCTime() != null ? String.valueOf(orderLists.get(j).getMeetCTime()) : "");
                                        resultOrderList.get(j).setDriverInPlaceTime(orderLists.get(j).getDriverInPlaceTime() != null ? String.valueOf(orderLists.get(j).getDriverInPlaceTime()) : "");
                                        resultOrderList.get(j).setEndJourneyTime(orderLists.get(j).getEndJourneyTime() != null ? String.valueOf(orderLists.get(j).getEndJourneyTime()) : "");
                                        resultOrderList.get(j).setStartJourneyTime(orderLists.get(j).getStartJourneyTime() != null ? String.valueOf(orderLists.get(j).getStartJourneyTime()) : "");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return resultOrderList;
    }


    /**
     * 多线程任务逻辑处理
     *
     * @param dealQueue
     * @param orderList
     */
    private HashMap<String, Object> executorDeal(String dealQueue, OrderList orderList, List<Long> offices) {
        if (Objects.equals(dealQueue, "one")) {
            log.info("处理第一个SQl查询开始：{}", Thread.currentThread().getName());
            List<OrderList> orderLists = cmsOrderInfoExportServer.orderInfoGroupOne(orderList, offices);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("dealQueue", "one");
            hashMap.put("results", orderLists);
            log.info("处理第一个SQl查询结束：{}", Thread.currentThread().getName());
            return hashMap;
            // 插入execl数据
        } else if (Objects.equals(dealQueue, "two")) {
            log.info("处理第二个SQl查询开始：{}", Thread.currentThread().getName());
            List<OrderList> orderLists = cmsOrderInfoExportServer.orderInfoGroupTwo(orderList, offices);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("dealQueue", "two");
            hashMap.put("results", orderLists);
            log.info("处理第二个SQl查询结束：{}", Thread.currentThread().getName());
            return hashMap;
        } else if (Objects.equals(dealQueue, "three")) {
            log.info("处理第三个SQl查询开始：{}", Thread.currentThread().getName());
            List<OrderList> orderLists = cmsOrderInfoExportServer.orderInfoGroupThree(orderList, offices);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("dealQueue", "three");
            hashMap.put("results", orderLists);
            log.info("处理第三个SQl查询结束：{}", Thread.currentThread().getName());
            return hashMap;
        } else if (Objects.equals(dealQueue, "four")) {
            log.info("处理第四个SQl查询开始：{}", Thread.currentThread().getName());
            List<OrderList> orderLists = cmsOrderInfoExportServer.orderInfoGroupFour(orderList, offices);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("dealQueue", "four");
            hashMap.put("results", orderLists);
            log.info("处理第四个SQl查询结束：{}", Thread.currentThread().getName());
            return hashMap;
        } else if (Objects.equals(dealQueue, "five")) {
            log.info("处理第五个SQl查询开始：{}", Thread.currentThread().getName());
            List<OrderList> orderLists = cmsOrderInfoExportServer.orderInfoGroupFive(orderList, offices);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("dealQueue", "five");
            hashMap.put("results", orderLists);
            log.info("处理第五个SQl查询结束：{}", Thread.currentThread().getName());
            return hashMap;
        } else if (Objects.equals(dealQueue, "six")) {
            log.info("处理第六个SQl查询开始：{}", Thread.currentThread().getName());
            List<OrderList> orderLists = cmsOrderInfoExportServer.orderInfoGroupSix(orderList, offices);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("dealQueue", "six");
            hashMap.put("results", orderLists);
            log.info("处理第六个SQl查询结束：{}", Thread.currentThread().getName());
            return hashMap;
        } else if (Objects.equals(dealQueue, "seven")) {
            log.info("处理第七个SQl查询开始：{}", Thread.currentThread().getName());
            List<OrderList> orderLists = cmsOrderInfoExportServer.orderInfoGroupSeven(orderList, offices);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("dealQueue", "seven");
            hashMap.put("results", orderLists);
            log.info("处理第七个SQl查询结束：{}", Thread.currentThread().getName());
            return hashMap;
        }
        return null;
    }


    /**
     * 查询字典表的数据
     *
     * @param fieldName：字段名称
     * @param inValue：in查询值
     * @return
     */
    private List<OaSysDict> getDictList(String fieldName, List<String> inValue) {
        QueryWrapper<OaSysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(fieldName, inValue);
        queryWrapper.select(OaSysDict.LABEL, OaSysDict.VALUE, OaSysDict.TYPE);
        return oaSysDictMapper.selectList(queryWrapper);
    }

    /**
     * 查询城市字典表的数据
     *
     * @param fieldName：字段名称
     * @param inValue：in查询值
     * @return
     */
    private List<OaSysArea> getDictArea(String fieldName, List<String> inValue) {
        QueryWrapper<OaSysArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(fieldName, inValue);
        queryWrapper.select(OaSysArea.AD_CODE, OaSysArea.NAME);
        return oaSysAreaMapper.selectList(queryWrapper);
    }

    /**
     * 订单详情获取行程录音
     *
     * @param cmsOadOrderPersonalParam
     * @return
     */
    @Override
    public Rv getCmsOrderDetailRecording(CmsOadOrderPersonalParam cmsOadOrderPersonalParam) {
        if (CheckUtil.strIsEmpty(cmsOadOrderPersonalParam.getOrderNo())) {
            throw PangException.create(EErrorCode.missingArg);
        }
        Qd qd = Qd.create();
        QueryWrapper<DriverTripRecord> recordQueryWrapper = new QueryWrapper<>();
        recordQueryWrapper.select(DriverTripRecord.RECORD_URL);
        recordQueryWrapper.eq(DriverTripRecord.ORDER_NO, cmsOadOrderPersonalParam.getOrderNo());
        List<DriverTripRecord> recordList = driverTripRecordMapper.selectList(recordQueryWrapper);
        if (!recordList.isEmpty()) {
            if (CheckUtil.strIsNotEmpty(recordList.get(0).getRecordUrl())) {
                qd.add("recordUrl", recordList.get(0).getRecordUrl());
            } else {
                qd.add("recordUrl", "");
            }
        } else {
            qd.add("recordUrl", "");
        }
        // 30天过期
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -30);
        Date minDate = calendar.getTime();
        QueryWrapper<DriverTripRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(DriverTripRecord.RECORD_URL, DriverTripRecord.CREATE_TIME);
        queryWrapper.eq(DriverTripRecord.ORDER_NO, cmsOadOrderPersonalParam.getOrderNo());
        queryWrapper.gt(DriverTripRecord.CREATE_TIME, minDate);
        List<DriverTripRecord> tripRecordList = driverTripRecordMapper.selectList(queryWrapper);
        if (!tripRecordList.isEmpty()) {
            qd.add("overdue", "0");
        } else {
            qd.add("overdue", "1");
        }
        return Rv.wrap(qd);
    }

    @Override
    public Rv getCmsOrderListByDriverId(String target) {
        if (CheckUtil.strIsEmpty(target)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        String[] split = target.split(",");
        String driverId = split[0];
        Long thisOrderTime = Long.valueOf(split[1]);  //当前订单的预约时间戳
        //通过司机id查询预约类订单
        List<OaCOrderPersonal> driverOrderList = oaDOrderMapper.getDriverOrderList(driverId);
        //通过司机id查询包车订单
        List<DriverOrderCard> charterOrderList = oaDOrderMapper.getDriverCharterOrderList(driverId);
        List<DriverOrderCard> beforeOrderList = new ArrayList<>();
        List<DriverOrderCard> afterOrderList = new ArrayList<>();
        List resultList = new ArrayList<>();
        for (OaCOrderPersonal oaCOrderPersonal : driverOrderList
        ) {
            if (oaCOrderPersonal.getAppointment().getTime() > thisOrderTime &&
                    oaCOrderPersonal.getAppointment().getTime() <= (thisOrderTime + 6 * 60 * 60 * 1000) && afterOrderList.size() < 3) {
                //后六小时
                DriverOrderCard driverOrderCard = new DriverOrderCard();
                driverOrderCard.setOrderType(oaCOrderPersonal.getOrderType());
                driverOrderCard.setAppointment(oaCOrderPersonal.getAppointment());
                driverOrderCard.setDurationTime(oaCOrderPersonal.getDurationTime());
                driverOrderCard.setMilageDistance(oaCOrderPersonal.getMilageDistance());
                driverOrderCard.setStartAddress(oaCOrderPersonal.getStartAddress());
                driverOrderCard.setEndAddress(oaCOrderPersonal.getEndAddress());
                afterOrderList.add(driverOrderCard);
            }
            if (oaCOrderPersonal.getAppointment().getTime() >= (thisOrderTime - 6 * 60 * 60 * 1000) && beforeOrderList.size() < 3
                    && oaCOrderPersonal.getAppointment().getTime() <= thisOrderTime) {
                //前六小时
                DriverOrderCard driverOrderCard = new DriverOrderCard();
                driverOrderCard.setOrderType(oaCOrderPersonal.getOrderType());
                driverOrderCard.setAppointment(oaCOrderPersonal.getAppointment());
                driverOrderCard.setDurationTime(oaCOrderPersonal.getDurationTime());
                driverOrderCard.setMilageDistance(oaCOrderPersonal.getMilageDistance());
                driverOrderCard.setStartAddress(oaCOrderPersonal.getStartAddress());
                driverOrderCard.setEndAddress(oaCOrderPersonal.getEndAddress());
                beforeOrderList.add(driverOrderCard);
            }
        }
        for (DriverOrderCard charterOrderCard : charterOrderList
        ) {
            //后六小时
            if (charterOrderCard.getAppointment().getTime() > thisOrderTime &&
                    charterOrderCard.getAppointment().getTime() <= (thisOrderTime + 6 * 60 * 60 * 1000) && afterOrderList.size() < 3) {
                afterOrderList.add(charterOrderCard);
            }
            //前六小时
            if (charterOrderCard.getAppointment().getTime() >= (thisOrderTime - 6 * 60 * 60 * 1000) && beforeOrderList.size() < 3
                    && charterOrderCard.getAppointment().getTime() <= thisOrderTime) {
                beforeOrderList.add(charterOrderCard);
            }
        }
        resultList.add(beforeOrderList);
        resultList.add(afterOrderList);
        return Rv.wrap(resultList);
    }

    @Autowired
    private OaSysBillRuleGroupMapper oaSysBillRuleGroupMapper;

    @Override
    public Rv addNewOrder(OaCOrderPersonal oaCOrderPersonal) {
        long id = IDUtil.nextId();
        oaCOrderPersonal.setOrderNo(String.valueOf(id));
        oaCOrderPersonal.setPersonalId(id);
        oaCOrderPersonal.setOrderStatus(EOrderStatus.waitingResponse.getType());
        oaCOrderPersonal.setIsCarpool(0);
        oaCOrderPersonal.setOrderTime(new Date());
        oaCOrderPersonal.setActualFee(new BigDecimal(0));
        oaCOrderPersonal.setAwaitFee(new BigDecimal(0));
        oaCOrderPersonal.setBaseFee(new BigDecimal(0));
        oaCOrderPersonal.setDistanceFee(new BigDecimal(0));
        oaCOrderPersonal.setServiceFee(new BigDecimal(0));
        oaCOrderPersonal.setDurationFee(new BigDecimal(0));
        oaCOrderPersonal.setMileageFee(new BigDecimal(0));
        oaCOrderPersonal.setStartFee(new BigDecimal(0));
        oaCOrderPersonal.setBaseSupplementFee(new BigDecimal(0));
        oaCOrderPersonal.setChannelProportionFee("0");
        oaCOrderPersonal.setBaseSupplementFee(new BigDecimal(0));
        oaCOrderPersonal.setDurationFee(new BigDecimal(0));
        oaCOrderPersonal.setCouponDeductionFee(new BigDecimal(0));
        oaCOrderPersonal.setEmptyDrivingFee(new BigDecimal(0));
        String realPhone = oaCOrderPersonal.getPassengerPhone();
        int plength = realPhone.length();
        String phoneSuffix = realPhone.substring(plength - 4, plength);
        oaCOrderPersonal.setPassengerPhoneSuffix(phoneSuffix);
        //查询抽成进行计算
        QueryWrapper<OaSysBillRuleGroup> queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaSysBillRuleGroup.CITY_ID, oaCOrderPersonal.getCityId());
        OaSysBillRuleGroup oaSysBillRuleGroup = oaSysBillRuleGroupMapper.selectOne(queryWrapper);
        if (oaSysBillRuleGroup == null) {
            return Rv.error(EErrorCode.unData);
        }
        Integer drawRatio = oaSysBillRuleGroup.getDrawRatio();
        BigDecimal totalFee = oaCOrderPersonal.getTotalFee();
        BigDecimal drawFee = totalFee.subtract(totalFee.multiply(new BigDecimal(drawRatio)).
                divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        oaCOrderPersonal.setDrawFee(drawFee.setScale(2, BigDecimal.ROUND_UP).setScale(2, RoundingMode.HALF_UP));
        oaCOrderPersonal.setCreateTime(new Date());
        oaCOrderPersonal.setCreateUser(String.valueOf(TokenUtil.getTokenUserId()));
        oaCOrderPersonal.setUpdateTime(new Date());
        oaCOrderPersonal.setUpdateUser(String.valueOf(TokenUtil.getTokenUserId()));
        oaCOrderPersonal.setVersion(0L);
        QueryWrapper<OaSysUser> officeQueryWrapper = new QueryWrapper<>();
        officeQueryWrapper.eq(OaSysUser.SYS_USER_ID, TokenUtil.getTokenUserId());
        OaSysUser oaSysUser = oaSysUserMapper.selectOne(officeQueryWrapper);
        if (oaSysUser == null) {
            return Rv.error(EErrorCode.unData);
        }
        String officeId = getOfficeId(oaCOrderPersonal.getCityId(), ETongChengRideType.getByType(oaCOrderPersonal.getVehicleType()).getValue()).toString();
        if (StringUtil.isEmpty(officeId)) {
            return Rv.error(EErrorCode.noneOffice);
        }
        oaCOrderPersonal.setOfficeId(officeId);
        int insert = oacOrderPersonalMapper.insert(oaCOrderPersonal);
        if (insert > 0) {
            return Rv.wrap();
        } else {
            return Rv.error(EErrorCode.addError);
        }
    }

    @Override
    public Rv cancleOrder(String orderNo) {
        UpdateWrapper<OaCOrderPersonal> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set(OaCOrderPersonal.ORDER_STATUS, EOrderStatus.officeCancelOrder.getType());
        updateWrapper.eq(OaCOrderPersonal.ORDER_NO, orderNo);
        int i = oacOrderPersonalMapper.update(null, updateWrapper);
        if (i > 0) {
            return Rv.wrap();
        } else {
            return Rv.error(EErrorCode.addError);
        }
    }

    public Long getOfficeId(String cityCode, Integer rideType) {
        Long officeId = 0L;
        List<com.xnyzc.lhy.order.entity.sidebar.OaSysOffice> companysByAdCode = oaSysOfficeMapper.getCompanysByAdCode(cityCode);
        if (CheckUtil.collectionIsEmpty(companysByAdCode)) {
            return null;
        }
        if (companysByAdCode.size() == 1) {//如果只有一个运力，直接返回
            return companysByAdCode.get(0).getOfficeId();
        }
        Map<String, Integer> drawMap = new HashMap<>(16);
        for (Iterator<com.xnyzc.lhy.order.entity.sidebar.OaSysOffice> oaSysOfficeIterator = companysByAdCode.iterator(); oaSysOfficeIterator.hasNext(); ) {
            com.xnyzc.lhy.order.entity.sidebar.OaSysOffice office = oaSysOfficeIterator.next();
            if (CheckUtil.strIsEmpty(office.getExpand1())) {
                continue;
            }
            String[] split = office.getExpand1().split(",")[rideType].split(":");
            String k = office.getOfficeId().toString();
            int v = Integer.valueOf(split[1]);
            drawMap.put(k, v);
        }
        if (CheckUtil.mapIsEmpty(drawMap)) {
            officeId = companysByAdCode.get(0).getOfficeId();
        } else {
            officeId = Long.parseLong(LuckDrawUtil.weightRandom(drawMap));
        }
        return officeId;
    }

    /**
     * 订单操作日志入库
     **/
    private void operateLog(OaCOrderPersonal personal, TokenUser tokenUser, String description, Function<String, Object> function) {
        threadPoolExecutor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    if (CheckUtil.objIsEmpty(tokenUser)) {
                        throw PangException.create(EErrorCode.nullData);
                    }
                    String username = "";
                    if (CheckUtil.objIsNotEmpty(tokenUser.getRoles())) {
                        OaSysUser user = oaSysUserMapper.selectOne(Qw.create().eq(com.xnyzc.lhy.order.entity.system.OaSysUser.SYS_USER_ID, tokenUser.getTokenUserId()));
                        if (null == user) {
                            throw PangException.create(EErrorCode.nullData);
                        }
                        username = StringUtils.isBlank(user.getName()) ? user.getLoginName() : user.getName();
                    } else {
                        OaDUser oaDUser = oadUserMapper.selectById(tokenUser.getTokenUserId());
                        if (null == oaDUser) {
                            throw PangException.create(EErrorCode.nullData);
                        }
                        username = StringUtils.isBlank(oaDUser.getDriverName()) ? "ID:" + tokenUser.getTokenUserId() + "未设置名字" : oaDUser.getDriverName();
                    }
                    OrderLogMo orderLogVO = OrderLogMo
                            .builder()
                            .id(IDUtil.nextId())
                            .orderNo(personal.getOrderNo())
                            .officeId(Long.valueOf(personal.getOfficeId()))
                            .orderStatus(personal.getOrderStatus())
                            .operatorId(tokenUser.getTokenUserId())
                            .operator(username)
                            .operateTime(LocalDateTime.now())
                            .description(username + " " + (Objects.nonNull(function) ? function.apply(description) : description))
                            .build();
                    producer.sendMsg(orderLogVO, LOG_OPERATE_ORDER, null, 1);
                } catch (Exception e) {
                    log.error("发送订单日志异常:", e);
                }
            }
        });
    }

}
